External razor views can't see external models

2019-03-05 07:46发布

问题:

I have a problem with external razor views. In my project I have main mvc web assembly and dynamically loaded external class library assemblies(from DB) with their own Controllers, Views and Models. These assemblies are not directly referenced and loaded at runtime.

I was able to make the whole system work by creating a custom controller factory for Controllers, a custom virtual path provider for Views. The views are embedded resources in my external assemblies.

The problem I have is when I create a strongly-typed external View with a model class from an external assembly the view cannot be compiled at runtime, because the assembly is not passed to the razor compiler. So I get the following error:

Compiler Error Message: CS0234: The type or namespace name 'MyPlugin' does not exist in the namespace 'MyNamespace' (are you missing an assembly reference?)

Source Error:

public class
_Page_ExternalViews_MyController_MyAction_cshtml : System.Web.Mvc.WebViewPage<MyNamespace.MyPlugin.Models.MyModel>
{

It works fine when I use a dynamic model, a model class from my main web assembly or from assemblies referenced directly in my web project. I know for sure that external assembly is loaded before the external razor views are compiled, since my controllers work just fine.

I started looking at RazorGenerator project to precompile my external Views, but wasn't able to make any progress (nothing is being generated) and I'm not even sure if I'm looking in the right direction, since my assemblies are loaded at runtime and I have to use my own ViewEngine and ControllerFactory.

回答1:

Try use the using directive in your Views in the dynamic assembly.

@using MyNamespace.MyPlugin.Models;
@using MyNamespace.MyPlugin;

etc



回答2:

I was able to precompile views with RazorGenerator Visual Studio extension (not RazorGenerator.Mvc one) in my assemblies.

It basically converts .cshtml razor views into .cs files with WebViewPage classes before assemblies compile. And in my web project I had to implement my own VirtualPathProviderViewEngine similar to this one