External razor views can't see external models

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.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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

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


Solution 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

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply