简体   繁体   中英

Precompiled Views and CompilationCallback

I've defined a compilation callback for my MVC views like

var mvc = services.AddMvc();
mvc.AddRazorOptions(razorSetup => {
    razorSetup.CompilationCallback = context => {
        // context.Compilation = context.Compilation.AddReferences(...)
    };
});

This works great - and while debugging, there's no problem - but when the build-tools are precompiling the views ( and as of asp.net core 2, precompiling is the default behavior ), the compilation callback is just not used anymore.

While this makes perfect sense to me (after a bit of struggling), I wan't to know how/where I can configure the precompilation task.

I finally found a solution...

.net core 2

In .net core 2 you can add a --configure-compilation-type= -Option to the respone file used during compilation. The value should be a fully qualified type that implements Microsoft.AspNetCore.Mvc.IDesignTimeMvcBuilderConfiguration (not sure if it's necessarry or if it's sufficient to have a Configure-method here)

Adding can be done via

<Target Name="_AddMvzRazorPrecompileOptions" AfterTargets="_CreateResponseFileForMvcRazorPrecompile">
    <Error Condition="!Exists($(_MvcRazorResponseFilePath))" Text="File $(_MvcRazorResponseFilePath) does not exist" />

    <ItemGroup>
        <_Option Include="--configure-compilation-type=KlugeSoftware.Web.ViewTranslator.PrecompileFactory, KlugeSoftware.Web.ViewTranslator" />
    </ItemGroup>

    <WriteLinesToFile File="$(_MvcRazorResponseFilePath)" Lines="@(_Option)" Overwrite="false" />
</Target>

.net core 3

Not that easy (at least I didn't find anything so far). But you can use a similar way to get your code between razor generation (creation of *.g.cs - files) and compiling them.

<Target Name="_DoSomethingSpecial" AfterTargets="PrepareForRazorCompile" BeforeTargets="RazorCoreCompile">
    <!-- ... -->
</Target>

At this point, you can use a custom msbuild task to inspect or modify the generated code (and/or the source code). Source files are stored in @(RazorCompile) , dependencies in @(RazorReferencePath) ....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM