MVC 6 RC2 Controllers in another assembly

后端 未结 3 751
粉色の甜心
粉色の甜心 2021-01-04 18:07

In MVC 6 RC1 we used the IAssemlbyProvider interface to register assemblies that were discovered at runtime and inject additional controller types, in a similar

相关标签:
3条回答
  • 2021-01-04 18:42

    I used Application Part using following builder extension method to implement Plugins functionality. I hope it would be useful for somebody.

    ASP.NET CORE 1.1

    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using System.IO;
    using System.Runtime.Loader;
    
    namespace AppPartTest1.Web.Helpers.Features
    {
        public static class FeaturesBuilderExtensions
        {
            //
            // Summary:
            //     Adds Features supports to the Application.
            //
            // Parameters:
            //   builder:
            //     The Microsoft.Extensions.DependencyInjection.IMvcBuilder.
            public static IMvcBuilder AddFeaturesSupport(this IMvcBuilder builder, IConfigurationRoot Configuration, IHostingEnvironment environment)
            {
    
                var fileNames = Directory.GetFiles("Features", "*.dll");
    
                foreach (string fileName in fileNames)
                {
                    builder.AddApplicationPart(AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.Combine(environment.ContentRootPath, fileName)));
                }
    
                return builder;
            }
        }
    }
    

    Call

        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
    
            environment = env;
        }
    
        public IHostingEnvironment environment { get; set; }
        public IConfigurationRoot Configuration { get; }
    
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            var builder = services.AddMvc()
                .AddFeaturesSupport(this.Configuration, this.environment);
        }
    
    0 讨论(0)
  • 2021-01-04 18:52

    After some time spending working with the ControllerFeature directly with no result it was time to go back to basics.

    Basically at start up of the application controllers are registered into the controller feature container not from the controller feature. This is key, as you need to get the controllers registered.

    I was browsing the GitHub repository for RC2 and came across the ControllerFeatureProvider. As stated.

    Discovers controllers from a list of <see cref="ApplicationPart"/>
    

    And then has a method further down to PopulateFeature where we can see it grabs all the parts registered to the application and extracts the controller interfaces (the IsController() method is worth a review).

    /// <inheritdoc />
    public void PopulateFeature(
        IEnumerable<ApplicationPart> parts,
        ControllerFeature feature)
    {
        foreach (var part in parts.OfType<IApplicationPartTypeProvider>())
        {
            foreach (var type in part.Types)
            {
                if (IsController(type) && !feature.Controllers.Contains(type))
                {
                    feature.Controllers.Add(type);
                }
            }
        }
    }
    

    So now we know how the controllers are found, they come from an ApplicationPart registered to the application. Next question was how do we create an application part.

    After some review and trying to use dependency injection, manually adding the part to the application to get my parts registered I came across another concept.

    The interface IMvcBuilder has the extension method AddApplicationPart which adds an Assembly to the application parts. This is done by wrapping the assembly in an AssemblyPart application part. On review of the AssemblyPart this part returns all of the types found in the assembly to the calling part system (in our case the ControllerFeatureProvider).

    /// <inheritdoc />
    public IEnumerable<TypeInfo> Types => Assembly.DefinedTypes;
    

    Now something interesting with the AssemblyPart is the method GetReferencePaths()

    /// <inheritdoc />
    public IEnumerable<string> GetReferencePaths()
    {
        var dependencyContext = DependencyContext.Load(Assembly);
        if (dependencyContext != null)
        {
            return dependencyContext.CompileLibraries.SelectMany(library => library.ResolveReferencePaths());
        }
    
        // If an application has been compiled without preserveCompilationContext, return the path to the assembly
        // as a reference. For runtime compilation, this will allow the compilation to succeed as long as it least
        // one application part has been compiled with preserveCompilationContext and contains a super set of types
        // required for the compilation to succeed.
        return new[] { Assembly.Location };
    }
    

    It appears that the final piece of the puzzle is to enable preserveCompilationContext within the modules (or external assembly's) project.json file.

    "preserveCompilationContext": {
        "type": "boolean",
        "description": "Set this option to preserve reference assemblies and other context data to allow for runtime compilation.",
        "default": false
    }
    

    Finally the implementation and resolution for this became quite simple. Each of our external assemblies (or modules) are loaded through our ModuleManager class. This has a list of all referenced module assemblies. So in the ConfigureServices method in the Startup.cs file where the MVC is registered we simply call the extension method AddApplicationPart for each module assembly as.

    var mvcBuilder = services.AddMvc();
    foreach(var module in ModulesManager.ReferencedModules)
    {
        mvcBuilder.AddApplicationPart(module.ReferencedAssembly);
    }
    

    Once making these small changes my external controllers stopped returning a 404.

    0 讨论(0)
  • 2021-01-04 18:59

    Just add in Startup -> ConfigureServices

    services.AddMvc()
    .AddApplicationPart(typeof(OtherAssemblyController).GetTypeInfo().Assembly)
    .AddControllersAsServices();
    
    0 讨论(0)
提交回复
热议问题