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把依赖注入的各种情形都做了很好的封装,使得我们使用起来还是非常方便的。
本文介绍了NInject组件在.NET中的使用方法,并通过两个示例展示了如何实现控制反转(依赖注入)。第一个示例是一个简单的控制台应用程序,第二个示例则是在ASP.NET MVC中使用NInject进行控制器实例化的具体实现。
157

被折叠的 条评论
为什么被折叠?



