ASP.NET MVC + Ninject: InRequestScope
Asked Answered
H

1

0

I want to create 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 inject IPerRequestResourceProvider in few classes. But when I add breakpoint to PerRequestResourceProvider constructor I see that PerRequestResourceProvider is created three times during one request and not single per request. What's wrong?

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

Hispanicism answered 24/7, 2014 at 7:55 Comment(6)
if that's the case you should post a minimal - but complete - sample which reproduces the problem. So that we/you can either create a bug report @ ninject or help you solve the problem. You could create a minimal solution, upload and link it.Japha
@Japha I've added source code bitbucket.org/maximtkachenko/ninjectinrequestscope/srcHispanicism
@Japha I've fixed HomeController contsructor but result is the same: PerRequestResourceProvider constructor is called 3 times during request.Hispanicism
yes i observed that too. As far as i've found out yet, i would say that you did not integrated ninject correctly into the solution. It's too bad that ninject is not throwing an exception. I guess you need ninject.MVC3 or ninject.extensions.MVC5 or something like that. The ninject.web.common stuff is IMHO not getting initialized properly.Japha
see github.com/ninject/ninject.web.mvc on how to do thatJapha
@Japha I've installed Ninject.MVC4 and now it works properly. Thanks.Hispanicism
J
0

There are two issues with your code:

  1. Ninject is not getting initialized correctly. You need one of the Ninject.MVCx packages (according to the MVC version you are using). To configure it correctly, see: http://github.com/ninject/ninject.web.mvc

  2. You are injecting PerRequestResourceProvider (the class type), and not IPerRequestResourceProvider (the interface type) into HomeController, thus the .InRequestScope() defined on the IPerRequestResourceProvider binding is not taking any effect. Change the HomeController constructor to get the inteface type injected and you're good.


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

Japha answered 24/7, 2014 at 10:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.