Ninject.MVC3 Bootstrapper's Kernel property is marked as Obsolete. How can I get access to the kernel?

给你一囗甜甜゛ 提交于 2019-12-01 03:51:00
Remo Gloor

The reason why this has been marked Obsolete and will be changed to internal in future is that people tend to use Ninject as a service locator if it is possible to do so. But Service Locator is an antipattern that should not be used. And as we don't want to provide functionality that helps building badly designed software it will be removed in future.

If this needs a lot of changes in your code this is sign that your code is suffering from this malaise Dependency Injection wise and you really should change it to a better design.

  1. Limit your access to the kernel to a mimimum. There is almost no situation in MVC where you need something other than plain constructor injection. Therefore my first advice is to refactor to constructor injection where possible.
  2. For these very rare cases where you need access to the kernel to create other objects you should inject a factory to the class that needs the new instance and inject the kernel into this factory (if the Constructor has a Kernel parameter, it'll receive the instance doing the injecting).

If you really want to stay with service locator even if almost everyone will tell you not to, you will have to keep a static reference yourself.

If you have a class that (for some reason) needs to retrieve objects from the Ninject kernel, you can include the kernel as one of the injected properties/constructor parameters on the class. This pattern is better in the sense that you're explicitly declaring that a particular class is using the kernel, rather than always having it available as the service locator pattern does.

This assumes that Ninject automatically adds an instance binding of the kernel to itself. I know that it used to do this, but if it doesn't you can add the binding manually.

In ASP.NET MVC 3, I think DepedencyResolver is a clean way to get a service locator.

You could use the Common Service Locator as a service location hook into Ninject. The Common Service Locator only allows you to retrieve objects though, not inject objects that you already have. Of course you could hack around this restriction, but you could just as easily create a static class that exposes the Ninject kernel and reference that rather than the BootStrapper.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!