Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing pre-compiled views in asp.net core from another project/assembly

Following on from this question, I have now set up pre-compiled views in my asp.net core application which is compiling to a DLL from the command line using the

dotnet razor-precompile

command. I have then packaged it as a nuget package using

dotnet pack

and added the package as a reference to the project I’ve removed the views from. I have then created a new class which implements IViewLocationExpander and set this up in the setup.cs method of my project and I can see it searching my new location for the views. However, I don’t know what to put as the search path for a pre-compiled view, as there are no .cshtml files in there. I simply get an InvalidOperationException with the view not found.

Has anyone done this before or able to suggest how I may add these precompiled views to the search path?

Thanks

like image 449
LDJ Avatar asked Oct 30 '22 12:10

LDJ


1 Answers

I was amazed, it directly worked this way:

I just registered into my main project a custom ViewExpander:

services.AddMvc().AddRazorOptions(options =>
{
    options.ViewLocationExpanders.Clear();
    options.ViewLocationExpanders.Add(new TestViewLocationExpander());
};

The expander itself:

public class TestViewLocationExpander : IViewLocationExpander
{
    public void PopulateValues(ViewLocationExpanderContext context)
    {
    }

    public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }
        if (viewLocations == null)
        {
            throw new ArgumentNullException(nameof(viewLocations));
        }

        yield return "~/Test/Test.cshtml";
    }
}

Then I have referenced the *.PrecompiledViews.dll of my other project, which contains a Test/Test.cshtml.

And voila, every page in my main application was showing this one.

like image 139
Christian Gollhardt Avatar answered Nov 11 '22 08:11

Christian Gollhardt