Skip to content
This repository was archived by the owner on Dec 14, 2018. It is now read-only.
This repository was archived by the owner on Dec 14, 2018. It is now read-only.

Using taghelpers in razor views using a model type which is loaded runtime #4497

Closed

Description

@DavidEmanuelsen

Hi,

I have created an application which uses a custom fileprovider for loading razor views from disk / database, and these views uses models coming from an assembly which is loaded runtime. I've used the RazorViewEngineOptions.CompilationCallback to load this assembly and the compilation of the views works - except for when using asp-for etc. (The compilation callback was implemented as per the example given in #4423)

The model object is created using Activator.CreateInstance where the type is coming from the external assembly.

The errors I'm getting when using taghelpers are:

  • Type expected
  • Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type

These errors don't contain much detail, but I'm assuming the problem is related to the model type which is loaded runtime. Any suggestions on how I can get this to work is greatly appreciated.

Activity

  1. dougbu commented on Apr 18, 2016

    @dougbu
    Contributor

    If any of the above errors are actually thrown exceptions, please provide the stack traces.

  2. Eilon commented on Apr 18, 2016

    @Eilon
    Contributor

    @DavidEmanuelsen indeed, where are you seeing these errors, and can you show us any relevant code from your app?

  3. DavidEmanuelsen commented on Apr 19, 2016

    @DavidEmanuelsen
    Author

    I have project containing the model to be used which implements an interface which is also know by the running application. This project / class library is build seperately, and in the main application I create an instance of the model like this:

    Assembly externalAssembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath);
    var type = Type.GetType(serviceNamespace 
                + "." + serviceImplementationName 
                + "," + serviceNamespace);
    
    return (IServiceModel)Activator.CreateInstance(type);
    

    The compilation callback looks like this:

    services.Configure<RazorViewEngineOptions>(options =>
    {
            var previous = options.CompilationCallback;
            options.CompilationCallback = (context) =>
            {
                   previous?.Invoke(context);
                   MetadataReference[] references = serviceAssemblyReferences.ToArray();
    
                   context.Compilation = context.Compilation.AddReferences(references);
             };
    
             options.FileProviders.Add(new CustomFileProvider());
    });
    

    Where the serviceAssemblyReferences-list is populated with new items as needed before returning from the controller (creating new items using MetadataReference.CreateFromFile(path))

    I'm having some issues debugging the application at the moment (not able to run it directly from VS, and when I use dotnet publish I can't attach to the running process), but I will update with stacktraces as soon as I can get them. Currently I'm only getting what the developer exception page is showing me when using <input asp-for="FirstName" type="text" /> or @Html.EditorFor(m => m.FirstName)

    image

  4. DavidEmanuelsen commented on Apr 19, 2016

    @DavidEmanuelsen
    Author

    Just realized I can give the type using @Html.EditorFor<MyModelType, int>(...).. How can the same be done for the taghelpers?

  5. Eilon commented on Apr 19, 2016

    @Eilon
    Contributor

    @DavidEmanuelsen - any chance you can replicate this scenario without the custom assembly loads, file system, etc.? In other words, can you create a regular CSHTML file on disk that uses regular models in regular CS files? I'm guessing you'll hit the exact same error, but it might be easier to replicate and debug from that.

  6. dougbu commented on Apr 19, 2016

    @dougbu
    Contributor

    Just realized I can give the type using @Html.EditorFor<MyModelType, int>(...). How can the same be done for the tag helpers?

    What is the advantage you see in calling EditorFor() with explicit type parameters? Suggest focusing on why can't the compiler infer those parameters from the expression.

    In any case you'll need parentheses around the generic method call: @(Html.EditorFor<MyModelType, int>(...)).

    Tag helpers have no equivalent to this. While it's possible to explicitly create a ModelExpression containing the correct information e.g. CreateModelExpression(m => m.Name) that instance can't be assigned to an asp-for attribute value -- that value is always part of a lambda expression in the generated code.

  7. DavidEmanuelsen commented on Apr 20, 2016

    @DavidEmanuelsen
    Author

    I've tried reproducing it without any assembly loads etc, but no luck. I'm only able to reproduce it when loading the assembly containing the model runtime. I've created a simple project which illustrates my issue.

    Controller action:

    public ActionResult Index()
    {
         return View(Activator.CreateInstance(Type.GetType("ModelProject.MyModel,ModelProject")));
    }
    

    View (now contained within the running application instead of loading from a custom location):

    @model ModelProject.MyModel
    @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
    
    <input asp-for="MyProperty" type="text" />
    

    Startup:

        public class Startup
        {
            public static List<MetadataReference> serviceAssemblyReferences = new List<MetadataReference>();
    
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc();
                services.Configure<RazorViewEngineOptions>(options =>
                {
                    var previous = options.CompilationCallback;
                    options.CompilationCallback = (context) =>
                    {
                        previous?.Invoke(context);
    
                        context.Compilation = context.Compilation.AddReferences(serviceAssemblyReferences.ToArray());
                    };
                });
            }
    
            public void Configure(IApplicationBuilder app)
            {
                app.UseDeveloperExceptionPage();
                app.UseStaticFiles();
                app.UseMvcWithDefaultRoute();
            }
    
            public static void Main(string[] args)
            {
                var ctx = new MyAssemblyLoadContext();
                AssemblyLoadContext.InitializeDefaultContext(ctx);
    
                var host = new WebHostBuilder()
                    .UseDefaultHostingConfiguration(args)
                    .UseIISIntegration()
                    .UseKestrel()
                    .UseStartup<Startup>()
                    .Build();
    
                host.Run();
            }
        }
    
        public class MyAssemblyLoadContext : AssemblyLoadContext
        {
            protected override Assembly Load(AssemblyName assemblyName)
            {
                string path = "C:\\ServiceAssemblies\\" + assemblyName.Name + ".dll";
                Startup.serviceAssemblyReferences.Add(MetadataReference.CreateFromFile(path));
    
                return LoadFromAssemblyPath(path);
            }
        }
    

    The ModelProject-assembly is build seperatly, but it only contains one class as follows:

    public class MyModel
    {
        public int MyProperty { get; set; }
    
         public MyModel()
         {
             MyProperty = 1337;
         }
    }
    
  8. Eilon commented on Apr 20, 2016

    @Eilon
    Contributor

    @dougbu can you try to repro and see what this error is about?

  9. dougbu commented on Apr 20, 2016

    @dougbu
    Contributor

    @Eilon 🆗

  10. dougbu commented on May 2, 2016

    @dougbu
    Contributor

    I can reproduce this compilation error without the custom AssemblyLoadContext.

    The CSharpCompilation change is at least partially doing the Right Thing™️. Without the added MetadataReference, Roslyn errors include The type or namespace name 'ModelProject' could not be found (are you missing a using directive or an assembly reference?).

    Hard to tell exactly what's going wrong due to the messed-up line numbers in the errors. But based on the columns and the general class of compilation failures, problems seem focused on ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.MyProperty); in the generated code. ViewData is of type ViewDataDictionary<ModelProject.MyModel> and the lambda is of type Expression<Func<ModelProject.MyModel, int>>. The compiler must be having problems inferring these types.

    Will continue looking.

    /cc @davidfowl any suggestions on where to go next?

  11. sebastienros commented on May 5, 2016

    @sebastienros
    Member

    One of Orchard's contributor had to move the compilation callback call to fix a related issue regarding compiling Views with references to dynamically loaded assemblies:

    https://files.gitter.im/OrchardCMS/Orchard2/6xVS/roslyn.png

  12. added this to the 1.0.0 milestone on May 5, 2016
  13. 22 remaining items

  14. NTaylorMullen commented on Jun 1, 2016

    @NTaylorMullen
  15. DavidEmanuelsen commented on Jun 29, 2016

    @DavidEmanuelsen
    Author

    @NTaylorMullen

    I've started the move to 1.0.0 and trying to use the new AdditionalCompilationReferences to add the MetadataReferences that I need. It works fine as long as I populate it during initial setup in Startup.cs, but if I inject the RazorViewEngineOptions somewhere else and update the list in the same request as the MetadataReference is needed it doesn't always work. It's kind of odd as it seems it works sometimes, but not all.

    It might be asking too much, but is it possible to get an example of how to manage the list of additional references correctly? I'm trying to get my head around the compilation works (and also how to use AssemblyLoadContext correctly), but I'm struggling a bit to find documentation / examples on these things.

    Just to give some context around what we are trying to achieve:
    We are creating a platform where users can create Views and logic which we will load from some database after the application has started as needed. So both the viewmodel and the views themselves are located / loaded runtime and are not known by the application when it starts.

    Our current plan for loading the views is using a custom FileProvider, and for the assemblies we're currently loading them from a db, placing on disk, loading using AssemblyLoadContext (the Default one) and also now creating a MetadataReference and add it to AdditionalCompilationReferences before returning the view. The model is created using Activator.CreateInstance(..) after the assembly has been loaded.

    I've created a test project which illustrates the behavior we are seeing here. After starting the application, /Secondary/Index is not able to resolve the reference to the external assembly if /Home/Index has loaded first. However, if I start the application and go /Secondary/Index straight away things works as expected (also for subsequent page loads / navigation). This confuses me, what's going on? :)

    I guess you are all currently out celebrating the launch, but any help / input / suggestions would be greatly appreciated.

  16. pranavkm commented on Jun 29, 2016

    @pranavkm
    Contributor

    but if I inject the RazorViewEngineOptions somewhere else and update the list in the same request as the MetadataReference is needed it doesn't always work

    Modifying any of the option types after Startup has done is not supported. Types are free to cache individual properties of the options, so updating it would not necessarily work all the time.
    For your scenario, I'd recommend not relying on modifying the options. If your app requires runtime compilation behavior, add a custom ICompilationService to the service collection (overriding Mvc's default implementation). You could derive from DefaultRoslynCompilationService and override GetCompilationReferences to specify your assembly list. However note that the type is in the .Internal namespace and we do not have guarantee compatibility between releases. Feel free to file a bug to move this to the public namespace.

  17. DavidEmanuelsen commented on Jun 30, 2016

    @DavidEmanuelsen
    Author

    Tried the suggested approach, and as far as I can tell it gives similar behavior as when I was using the option. Debugging this shows one call to my overridden GetCompilationReferences as the first request comes in (before the external assembly is needed / known), and the result of this first invoke seems to be used when compiling my views using the external classes. Returning a view using this model results in a resolve-failure.

    At least when I was using Compilation.AddReferences in the CompilationCallback-approach I was able to have the views resolve the types successfully in this scenario (except for the issue this bug was originally for :)).

    protected override IList<MetadataReference> GetCompilationReferences()
            {
                // Get all base references
                IList<MetadataReference> baseReferences = base.GetCompilationReferences();
    
                if (AdditionalReferences.Count == 0)
                {
                    return baseReferences;
                }
    
                var compilationReferences = new List<MetadataReference>(baseReferences.Count + AdditionalReferences.Count);
                compilationReferences.AddRange(baseReferences);
                compilationReferences.AddRange(AdditionalReferences);
    
                return compilationReferences;
            }
    

    Edit: Now with implementation

  18. dougbu commented on Jun 30, 2016

    @dougbu
    Contributor

    @DavidEmanuelsen you'll need to do more than override GetCompilationReferences(). Unfortunately you'll need to copy most of DefaultRoslynCompilationService and replacing the CompilationReferences property with something that is not lazy-inited.

  19. DavidEmanuelsen commented on Jun 30, 2016

    @DavidEmanuelsen
    Author

    Ok, that works as expected 👍 Although I guess there will be some increased risk of breaking changes in the future as I depend on .Internal.. (ExpressionRewriter, IRazorViewEngineFileProviderAccessor). Is there any chance at all that these can be moved, or is there any obvious way I can avoid using these directly that I don't see?

    Also, will there be any significant performance hit when omitting the lazy-init?

  20. pranavkm commented on Jun 30, 2016

    @pranavkm
    Contributor

    @DavidEmanuelsen, like I mentioned earlier, feel free to file a bug to move the type (and it's dependencies) into a public namespace.

    Also, will there be any significant performance hit when omitting the lazy-init?

    I think creating MetadataReferences reads the entire assembly into memory (along with creating Roslyn object graphs for everything within the assembly). This can be pretty memory expensive, part of the reason we lazy initialized and cached the results.

  21. added 2 commits that reference this issue on Feb 22, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions