NInject组件的使用及探究

NInject组件是.NET中实现控制反转(依赖注入)的组件。今天学习了一下NInject组件的使用,分别写了一个入门级别的Demo并且探究了下在ASP.NET MVC 中Controller加载过程中是如何使用NInject的。

1.NInject Demo

using System.Text;
using System.Threading.Tasks;
using Ninject;

namespace NInjectDemo
{
    interface ILogService
    {
        void PrintLog();
    }

    class LogService : ILogService
    {
        public void PrintLog()
        {
            Console.WriteLine("I am printing log.");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            IKernel kernel = new StandardKernel();
            kernel.Bind<ILogService>().To<LogService>();
            var logService = kernel.Get<ILogService>();
            logService.PrintLog();

            Console.ReadKey();
        }
    }
}
代码非常简洁,我们需要一个接口和一个实现了接口的类,然后我们使用IKernel的实例去绑定,然后获取实例,最后调用方法!

I am printing log.
2.在ASP.NET MVC 中通过一个kernel去获取所有继承自IController的对象的实例!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Ninject;

namespace AspNetMvcNInjectDemo
{
    interface ILogService
    {
        string PrintLog();
    }

    class LogService : ILogService
    {
        public string PrintLog()
        {
            return "I am printing log.";
        }
    }

    class NInjectControllerFactory : DefaultControllerFactory
    {
        private readonly IKernel _kernel;

        public NInjectControllerFactory()
        {
            _kernel = new StandardKernel();
            //AddBindings();
        }

        /*
        private void AddBindings()
        {
            _kernel.Bind<ILogService>().To<LogService>();
        }
        */

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            return controllerType == null ? null : (IController)_kernel.Get(controllerType);
        }
    }

    public class MvcApplication : HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            ControllerBuilder.Current.SetControllerFactory(new NInjectControllerFactory());
        }
    }
}

这与我在蒋金楠编写的《ASP.NET MVC5框架揭秘》中看到的关于ASP.NET MVC Controller的加载机制是一致的!

NInject把依赖注入的各种情形都做了很好的封装,使得我们使用起来还是非常方便的。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值