依赖注入的简单介绍
依赖注入不是目的,它是一系列工具和手段,最终的目的是帮助我们开发出松散耦合(loose coupled)、可维护、可测试的代码和程序。这条原则的做法是大家熟知的面向接口,或者说是面向抽象编程。
依赖注入的具体实例
1.在Nuget添加Ninject
2.在Global中添加注入
DependencyResolver.SetResolver(new NinjectDependencyResolver());// 注册Ninject依赖注入容器
3.添加注入类NinjectDependencyResolver
public class NinjectDependencyResolver : IDependencyResolver { private IKernel kernel; //容器引擎 public NinjectDependencyResolver() { kernel = new StandardKernel(); kernel.Settings.InjectNonPublic = true; // 非public属性注入 AddBindings(); } private void AddBindings() { this.kernel.Bind<IClassRepository>().To<ClassRepository>(); this.kernel.Bind<IUserRepository>().To<UserRepository>(); } #region IDependencyResolver Members public object GetService(Type serviceType) { return kernel.TryGet(serviceType); } public IEnumerable<object> GetServices(Type serviceType) { return kernel.GetAll(serviceType); } #endregion }
4.在basecontroller里面添加注入
#region inject依赖注入 [Inject] protected IClassRepository ClassRepository { get; set; } [Inject] protected IUserRepository UserRepository { get; set; } #endregion
5.在具体的controller调用即可