Using strongly typed Razor views with view models loaded at runtime

时间:2019-01-07 12:54:53

标签: .net razor .net-core asp.net-core-mvc asp.net-core-2.0

I would like to be able to use strongly-typed Razor views with models and controllers loaded at runtime. The assemblies are loaded during application startup in ConfigureServices via anIApplicationFeatureProvider.

        services.AddMvc()
           .ConfigureApplicationPartManager(apm => apm.FeatureProviders.Add(new DynamicControllerFeatureProvider()));

Views with a model type of dynamic will compile just fine, but any strongly typed Razor views do not compile.

The type or namespace name 'TestModules' does not exist in the namespace 'TestProject' (are you missing an assembly reference?)

How can I make the Razor engine aware of the dynamically loaded assemblies so I can use strongly typed views? It seems like using a custom RazorBuildProvider would work, but is there a better aproach?

1 个答案:

答案 0 :(得分:1)

剃刀视图默认情况下是预编译的。由于必需的程序集在运行时才可用,因此无法进行预编译。您需要在csproj中使用以下命令将其关闭:

<PropertyGroup>
    <RazorCompileOnBuild>false</RazorCompileOnBuild>
    <RazorCompileOnPublish>false</RazorCompileOnPublish>
</PropertyGroup>