McMlok
McMlok

Reputation: 537

Change VirtualPathProvider in MVC 5

I ported my MVC 4 project to MVC 5 and after that my views with is embedded as resources cannot be loaded. Problem is that when mvc search for view it uses view engine witch inherit from BuildManagerViewEngine. This class use FileExistenceCache with use VirtualpathProvider with is set through constructor. By default its MapPathBased provider when I change provider to my custom in HostingEnviroment no change is made in existing FileExistenceCache instances than my view is not founded.

I change VirtualpathProvider in Route config class but its to late. What is better place for this?

Thanks

Upvotes: 2

Views: 2311

Answers (1)

Nenad
Nenad

Reputation: 26717

Rather subclass existing 'IViewEngine' to use custom VirtualPathProvider. Then register your custom engine in Global.asax file.

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        ViewEngines.Engines.Add(new MyViewEngine());
    }

    private class MyVirtualPathProvider: VirtualPathProvider {}

    private class MyViewEngine : RazorViewEngine
    {
        public MyViewEngine()
        {
            this.VirtualPathProvider = new MyVirtualPathProvider();
        }
    }
}

This way you can also control which engine has priority by adding, inserting your engine at proper place in Engines collection.

As an alternative, you can use PreApplicationStartMethodAttribute to replace VirtualPathProvider, but this will change provider globally, for all standard IViewEngines.

[assembly: PreApplicationStartMethod(
    typeof(MyNamespace.MyInitializer), "Initialize")]

Then you swap provider in public static method in your class:

public static class MyInitializer
{
    public static void Initialize() { 
        HostingEnvironment.RegisterVirtualPathProvider(new MyVirtualPathProvider());
    }
}

There is good post by Phil Haack about it: Three Hidden Extensibility Gems in ASP.NET 4

Upvotes: 2

Related Questions