1

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?

user369117
  • 775
  • 1
  • 8
  • 19

2 Answers2

1

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.

Tim
  • 497
  • 3
  • 9
  • I'm trying some things for a multi tennant website. I want to be able to have different Themes. So each tennant has it's own css and masterpage. I thought it was a good idea to detect the tennant on each request, and create the viewengine with it. – user369117 Oct 28 '11 at 17:06
0

Rather then injecting the custom view engine, could you try using Application_Start() instead:

protected void Application_Start()
{
   ViewEngines.Engines.Clear();
   ViewEngines.Engines.Add(new RazorViewEngineProvider());
   RegisterRoutes(RouteTable.Routes);
}

What happens when you do the registration this way? Does it work?

Jason Evans
  • 28,906
  • 14
  • 90
  • 154
  • Yes, registration like that works. But it's not completely what I want. I want to refresh the ViewEngine every request. I've looked at the global_asax methods, of which BeginRequest looks the most relevant. But I would like to use a dependency from Ninject, and I can't get to the Ninject Kernel from global_asax. – user369117 Oct 28 '11 at 15:33
  • I've replicated your problem, indeed, the `CreateInstance` method is only called once for me too. Not sure about this one I'm afraid. – Jason Evans Oct 28 '11 at 16:00