Vincent
Vincent

Reputation: 958

How to share Views between ASP.NET vNext MVC 6 (beta1) projects?

In MVC5 it was possible to share Views (Razor) between projects by using a tool like Razor Generator ( http://razorgenerator.codeplex.com ). How to achieve the same in vNext? My Views aren't recognized out of the box (the project containing views is listed as a dependency in project.json).

InvalidOperationException: The partial view '~/Views/Authentication/_LogInForm.cshtml' was not found. The following locations were searched: ~/Views/Authentication/_LogInForm.cshtml

Upvotes: 4

Views: 2004

Answers (2)

Vincent
Vincent

Reputation: 958

We finally managed to solve this. Not quite easy though...

  1. You need to embed the views as resources in the project you'll depend on. To do this, add "resources": [ "**/*.cshtml" ] to its project.json.

  2. You need to create an IFileSystem that looks into those resources instead of looking on the disk. This is the tricky part. I put this on pastbin for lisibility: http://pastebin.com/aNfq5hNi

  3. You need to register this IFileSystem in your Startup.cs:

//... public void Configure(IApplicationBuilder app,IHostingEnvironment env,ILoggerFactory loggerfactory) { //Enable use of views in other assemblies IOptions<RazorViewEngineOptions> razorViewEngineOptions=app.ApplicationServices.GetService<IOptions<RazorViewEngineOptions>>(); razorViewEngineOptions.Options.FileSystem=new MVCAsset.EmbeddedExpiringFileInfoCache( razorViewEngineOptions, app.ApplicationServices.GetService<ILibraryManager>() ); //... } //...

NB : This is actually tested and working for MVC6 RC1, I didn't test for BETA1.

Upvotes: 3

Jeremy
Jeremy

Reputation: 1963

I'm not sure if this helps accessing views in external assemblies, but to add locations where views can be discovered you can implement IViewLocationExpander like this:

public class ViewLocationExpander : IViewLocationExpander
{
    public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
    {
        var locations = new List<string>(viewLocations);

        locations.Add("Views/MyOtherViewLocation/{0}.cshtml");

        return locations;
    }

    public void PopulateValues(ViewLocationExpanderContext context)
    {

    }
}

In your Startup.cs ConfigureServices method, add:

        services.Configure<RazorViewEngineOptions>(options =>
        {
            var expander = new ViewLocationExpander();
            options.ViewLocationExpanders.Add(expander);
        });

Upvotes: 2

Related Questions