从MVC3中就开始接触Ninject这个IOC工具。也一直是MVC Framework系列书籍中推荐的IOC工具,当然还有优秀的Autofac等。性能和使用上面个有千秋。下面先看一下Ninject的使用: 

    1.添加Ninject。工具-->Nuget程序包管理器-->程序包管理器控制台,输入下面的命令:

Install-Package Ninject -version 3.0.1.10
Install-Package Ninject.Web.Common -version 3.0.0.7
Install-Package Ninject.MVC3 -Version 3.0.0.6

  【读书笔记】Ninject 在MVC5中的使用 

  2.创建依赖分解器 NinjectDependencyResolver。

    NinjectDependencyResolver实现了IDependencyResolver接口,当一个请求进来的时候,MVC框架会调用GetService或GetServices方法去获取对象的实例去服务这个请求。GetAll方法支持单个类型的多重绑定。我们在AddBinds方法中添加接口的绑定。

 public class NinjectDependencyResolver : IDependencyResolver
    {
        private IKernel kernel;
        public NinjectDependencyResolver(IKernel kernelParam)
        {
            kernel = kernelParam;
            AddBindings();
        }
        public object GetService(Type serviceType)
        {
            return kernel.TryGet(serviceType);
        }
        public IEnumerable<object> GetServices(Type serviceType)
        {
            return kernel.GetAll(serviceType);
        }
        private void AddBindings()
        {   

               kernel.Bind<IProductRepository>().To<EFProductRepository>();
               kernel.Bind<IAuthProvider>().To<FormsAuthProvider>();

        }
    }

3.注册

 在MVC3,4中,我们是在Global的Application_Start()中注册。当应用启动的时候回触发Application_Start()中的方法。

 DependencyResolver.SetResolver(new NinjectDependencyResolver());

 那再MVC5中,更加完善。注意到我们之前引用了Ninject.Web.Common,这个是在MVC4以前没有出场的。它会在App_Start文件中创建一个NinjectWebCommon.cs类:

 它的Start方法是会先于Global的Application_Start()方法执行。

[assembly: WebActivator.PreApplicationStartMethod(typeof(NinjectWebCommon), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(NinjectWebCommon), "Stop")]
namespace SportsStore.WebUI
{
    public static class NinjectWebCommon 
    {
        private static readonly Bootstrapper bootstrapper = new Bootstrapper();
        /// <summary>
        /// Starts the application
        /// </summary>
        public static void Start() 
        {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
            DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
            bootstrapper.Initialize(CreateKernel);
        }
        
        /// <summary>
        /// Stops the application.
        /// </summary>
        public static void Stop()
        {
            bootstrapper.ShutDown();
        }
        
        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
       
            RegisterServices(kernel);
            return kernel;
        }

        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
            System.Web.Mvc.DependencyResolver.SetResolver(new Infrastructure.NinjectDependencyResolver(kernel));
        }        
    }
}

  它充分使用Asp.Net 4.0的新技术,并使用了WebActivator框架,在Web程序启动前动态调用Start函数,在关闭前调用Stop函数.在Start函数中,动态注册了OnePerRequestHttpModule和NinjectHttpModule.而对于CreateKernel函数,首先新建了IOC核心,然后绑定了Func<IKernel>类型与IHttpModule类型.

  5.绑定方法:

   1)基本绑定

kernel.Bind<IValueCalculator>().To<LinqValueCalculator>();

  2)传递参数:

  创建一个IDiscountHelper接口。让DefaultDiscountHelper 实现它。

public interface IDiscountHelper {
decimal ApplyDiscount(decimal totalParam);
}
public class DefaultDiscountHelper : IDiscountHelper {
public decimal DiscountSize { get; set; }
public decimal ApplyDiscount(decimal totalParam) {
return (totalParam - (DiscountSize / 100m * totalParam));
}
View Code

相关文章:

  • 2021-07-27
  • 2021-07-29
  • 2022-12-23
  • 2021-08-23
  • 2022-12-23
  • 2021-11-24
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-12-08
  • 2021-11-21
  • 2022-12-23
  • 2021-06-27
  • 2022-12-23
  • 2022-01-13
相关资源
相似解决方案