asp.net MVC4, Ninject automating
在MVC4下, 很多人都在使用Ninject来实现DI。
在这里( http://q.cnblogs.com/q/37471/ ) , 老大提到一个:
[assembly: PreApplicationStartMethod( typeof (BootStrapper.Initializer), "Initialize" )]
但是我至今都没搞定那个BootStrapper是怎么来的。引用了哪些DDL?
研究了2个小时,搞定如下:
1. 首先需要添加如下的引用: (添加到WebUI项目下,DAL项目无需添加)
1) BootStrapper.Ninject
2) Ninject.
使用nuget添加,其他关联的引用,会自动添加上来。
2. WebUI下,创建NinjectDependencyResolver.cs
内容如下:
public class NinjectDependencyResolver : IDependencyResolver
{
private IKernel ninjectKernel;
public NinjectDependencyResolver()
{
ninjectKernel = (IKernel)Bootstrapper.Container;
}
public object GetService(Type serviceType)
{
return ninjectKernel.TryGet(serviceType);
}
public IEnumerable< object > GetServices(Type serviceType)
{
return ninjectKernel.GetAll(serviceType);
}
}
3. Controller使用构造函数注入.
public class UserController : Controller
{
<strong> private IUserRepository repository;
public UserController(IUserRepository repo)
{
repository = repo;
}</strong>
//
// GET: /User/
public ViewResult Index()
{
return View(repository.AllUsers());
}
}
如果使用属性注入:
public class UserController : Controller
{
[Inject]
public IUserRepository Repository{ get ; set ;}
//
// GET: /User/
public ViewResult Index()
{
return View(Repository.AllUsers());
}
}
这个看起来更简洁。
4. 在Global.asax.cs中,修改Application_Start
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
<strong>Bootstrap.Bootstrapper.With.Ninject().UsingAutoRegistration().Start();
Bootstrap.Bootstrapper.IncludingOnly.Assembly(Assembly.GetAssembly( typeof (User)))
.Start();
//ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
DependencyResolver.SetResolver( new NinjectDependencyResolver());</strong>
BundleTable.Bundles.RegisterTemplateBundles();
}
解释:
1) Bootstrap.Bootstrapper.With.Ninject().UsingAutoRegistration().Start(); -- 这个主要是自动注册所有的类型,惯例是IMyType的默认实现是MyType(少一个I)。
如同:Kernel.Bind<IMyType>().To<MyType>();
但是在我们的例子里面,不需要写一句:Kernel.Bind<IMyType>().To<MyType>();。 只要保持这个惯例即可。
2) Bootstrap.Bootstrapper.IncludingOnly.Assembly(Assembly.GetAssembly(typeof(User)))
.Start(); -- 这个主要是仅仅加载我们的DAL文件, 不用去扫描其他文件,提高效率
希望给其他人一个更多的参考
enjoy it, :)
分类: .Net(c#,asp.net)
作者: Leo_wl
出处: http://www.cnblogs.com/Leo_wl/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
版权信息查看更多关于asp.net MVC4, Ninject automating的详细内容...