ASP.NET MVC + Ninject: InRequestScope

I want to create an instance of PerRequestResourceProvider using ninject InRequestScope:

public class PerRequestResourceProvider: IPerRequestResourceProvider { priavte readonly _perRequestResorceInstance; public PerRequestResourceProvider() { _perRequestResorceInstance = new PerRequestResource(); } public PerRequestResource GetResource() { return _perRequestResorceInstance; } } public interface IPerRequestResourceProvider { PerRequestResource GetResource(); } 

In my NinjectDependencyResolver:

 ..... kernel.Bind<IPerRequestResourceProvider>.To<PerRequestResourceProvider>().InRequestScope(); 

I injected IPerRequestResourceProvider into several classes. But when I add a breakpoint to the PerRequestResourceProvider constructor, I see that PerRequestResourceProvider is created three times in one request, and not in one request. What's wrong?

Update : source code ttps: //bitbucket.org/maximtkachenko/ninjectinrequestscope/src

0
source share
1 answer

There are two problems in the code:

  • Ninject does not receive the correct initialization. You need one of the Ninject.MVCx packages (according to the version of MVC used). To configure it correctly, see http://github.com/ninject/ninject.web.mvc

  • You enter the PerRequestResourceProvider (class type) and not IPerRequestResourceProvider (interface type) in the HomeController , so the .InRequestScope() defined in the IPerRequestResourceProvider binding has no IPerRequestResourceProvider HomeController constructor to get the entered inteface type, and you are fine.


Ninject does not require binding for instanceable (non-abstract, ..) classes. This is why it is not obvious when the wrong binding is used.

0
source

All Articles