ASP.NET MVC + Ninject: InRequestScope

2020-05-01 08:44发布

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

1条回答
爷、活的狠高调
2楼-- · 2020-05-01 09:22

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.

查看更多
登录 后发表回答