ASP.NET MVC + Ninject: InRequestScope

家住魔仙堡 提交于 2019-12-02 17:18:06

问题


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:


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.



来源:https://stackoverflow.com/questions/24928070/asp-net-mvc-ninject-inrequestscope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!