Looking for Ninject equivalent of StructureMap's ObjectFactory.GetInstance() method

南笙酒味 提交于 2019-11-30 16:10:46

问题


I'm using Ninject in an MVC project and I've used the autoregistration features in Ninject.Mvc and have my bindings set up in my application class. However, I have a place where I want to create an instance separate from those bindings. In StructureMap, you can do var foo = ObjectFactory.GetInstance<IFoo>(); and it will resolve it for you. Is there an equivalent in Ninject 2? I can't seem to find it anywhere.


回答1:


AFAIK, NInject doesn't have static method like this so all resolving should go to some kernel.

But you can implement it easily;

 class ObjectFactory
 {
     static IKernel kernel = new StandardKernel(.....);
     public static T GetInstance<T>()
     {
          return kernel.Get<T>();
     }
 }

Although, IMO, NInject is much more useful as DI container than as service locator.




回答2:


You can also use Common Service Locator as an abstraction layer for Ninject IOC which offers what you want. The advantage is that you can later switch container if it does not fit your needs anymore.

In your code you can use something like this:

ServiceLocator.Current.GetInstance<Type>();


来源:https://stackoverflow.com/questions/1576238/looking-for-ninject-equivalent-of-structuremaps-objectfactory-getinstance-met

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