3

How is it possible to use Ninject inside ASP.NET MVC 3 to instantiate objects manually? Something as

"NinjectObject".Resolve<IMyService>();

Thank you & regards

Bill
  • 2,026
  • 9
  • 55
  • 99

1 Answers1

14

It is better to inject dependencies instead of resolving them. Service Locator is an anti-pattern. You could for example use the following:

IMyService myService = DependencyResolver.Current.GetService<IMyService>();

But please do not use it. That's an anti-pattern.

Dependency injection is the preferred way. You should have the constructor of the class that needs this dependency take an IMyService instead of having the class fetch this dependency.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • That's what I am doing. I am creating a custom DependencyResolver based on Ninject, so I register all Interfaces with Ninject, but inside the custom DependencyResolver, I need to instantiate the interface with Ninject, that's what I need. – Bill May 26 '12 at 11:05
  • Guess i missed something here, Ninject registers itself as a custom DependencyResolver? I saw an example of a custom DependencyResolver based on MSFT Unity, where the code needed to resolve instances inside the custom DR. – Bill May 26 '12 at 11:06
  • Hi Darin, I had the case where I was implementing Start method of WebActivator, I needed an instance of a certain interface however, the class implementing WebActivator is Static and has no way to access an instance of that interface, what would be best way to do so? Thanks – Bill May 26 '12 at 19:18
  • 3
    @Darin Dimitrov You said doing this is an anti-pattern, is there any better way to get a service in a static method? – VahidNaderi Sep 22 '14 at 08:26
  • Thanks for answering how not to do it. But what if you need an instance from code? What is the answer? – Jonathan Wood Oct 16 '16 at 00:09