Finding the Ninject Equivalent of the StructureMap ObjectFactory.GetInstance () Method

I am using Ninject in an MVC project and I have used the auto update features in Ninject.Mvc and have set bindings in my application class. However, I have a place where I want to instantiate separately from these 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 anything.

+2


source to share


2 answers


AFAIK, NInject doesn't have a static method, so all permissions must go to some core.

But you can easily implement it;



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

      

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

+6


source


You can also use the Common Service Locator as an abstraction layer for the Ninject IOC that suggests what you want. The advantage is that you can switch the container later if it no longer suits your needs.

In your code, you can use something like this:



ServiceLocator.Current.GetInstance<Type>();

      

+1


source







All Articles