InRequestScope 提供程序(用于自定义 ViewEngine)仅在应用程序启动时调用一次
我想将自定义 ViewEngine 注入我的 MVC 网站。这就是我所做的:
private static IKernel CreateKernel()
{
kernel.Bind<IViewEngine>().ToProvider(new RazorViewEngineProvider()).InRequestScope();
}
这是我的提供商:
public class RazorViewEngineProvider : Provider<RazorViewEngine>
{
protected override RazorViewEngine CreateInstance(IContext context)
{
return new RazorViewEngine();
}
}
问题是:当我第一次访问该网站时,我的提供商仅被调用一次。下次我的提供者不知何故仍在缓存中。这不是我想要的。
我希望提供者执行每个请求。我以为我可以用 .InRequestScope() 做到这一点,但这没有任何区别。有谁知道发生了什么事吗?
I want to inject a custom ViewEngine into my MVC website. This is what I do:
private static IKernel CreateKernel()
{
kernel.Bind<IViewEngine>().ToProvider(new RazorViewEngineProvider()).InRequestScope();
}
This is my provider:
public class RazorViewEngineProvider : Provider<RazorViewEngine>
{
protected override RazorViewEngine CreateInstance(IContext context)
{
return new RazorViewEngine();
}
}
Problem is: My provider is only called once when I go to the website for the first time. The next time my provider is somehow still in cache. And that's not what I want.
I want the provider to execute on every request. I thought I could do that with .InRequestScope(), but that doesn't make any difference. Does anyone know what's going on?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这种情况下,Ninject 不会缓存视图引擎。 MVC 本身并不每次都向 IDependencyResolver 请求它。但我认为这是正确的行为。这样,通过重用它,可以将创建视图引擎的开销降至最低。
您的视图引擎中不应该有依赖于请求的依赖项。这种依赖关系必须从视图模型中检索,并由控制器分配。
并且您应该删除 InRequestScope。否则,它将在第一个请求后被 Ninject 处理,但 MVC 仍会尝试重用它。
The view engine isn't cached by Ninject in this case. It's MVC itsself that does not request it every time from the IDependencyResolver. But I think this is the correct behavior. That way it keeps the overhead to create the view engine at a minimum by reusing it.
You shouldn't have a request dependent dependency in your view engine. This kind of dependency has to be retrieved from the view model and has to be assigned by the controller.
And you should remove InRequestScope. Otherwise it will disposed by Ninject after the first request but MVC will still try to reuse it.
您可以尝试使用
Application_Start()
而不是注入自定义视图引擎:以这种方式进行注册时会发生什么?有效吗?
Rather then injecting the custom view engine, could you try using
Application_Start()
instead:What happens when you do the registration this way? Does it work?