ninject / Ninject.Web.Mvc

extension for ninject providing integration with ASP.NET MVC
http://ninject.org/
Other
238 stars 85 forks source link

Dependency Injection Outside Controller (MVC 4 Web API) #28

Closed Teagan42 closed 11 years ago

Teagan42 commented 11 years ago

I have an ApiController with the following constructor signature:

public BlazrController(BlazrDBContext dbContext, IAuthProvider authProvider, ILogger logger) { ... }

My bindings:

kernel.Bind<BlazrDBContext>().ToSelf().InRequestScope();
kernel.Bind<IHasher>().To<PasswordHasher>().InRequestScope();
kernel.Bind<IIPContextProvider>().To<DefaultIPContextProvider>().InRequestScope();
kernel.Bind<ILocationContextProvider>().To<DefaultLocationContextProvider>().InRequestScope();
kernel.Bind<ILogger>().To<FileLogger>().InRequestScope();
kernel.Bind<IAuthProvider>().To<BlazrAuthProvider>().InRequestScope();

And the IAuthProvider implementation (BlazrAuthProvider) has a constructor with signature:

public BlazrAuthProvider(BlazrDBContext dbcontext, IHasher hasher) {....}

When I run my application and navigate to a route under the ApiController above, I get the whole "No default constructor" error. I have removed the injected parameters from the constructors as to narrow down which one was causing the problem - and it was the IHasher under the BlazrAuthprovider. If I remove that from the constructor, it loads just fine.

I implemented a NinjectDependencyResolver (IDependencyResolver) as others have suggested but still can't get this to work. Am I missing something?

Also worth noting: the Controller is under it's own Web API Project and the other classes/interfaces are under a Class Library Project in the same solution.

remogloor commented 11 years ago

WebApi support is provided by https://github.com/ninject/Ninject.Web.WebApi not the MVC extension.

Questions about custom IDependencyResolver implementation are better asked in the user list or on stackoverflow.