MVC 6 RC2 Controllers in another assembly

后端 未结 3 781
粉色の甜心
粉色の甜心 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);
        }
    

提交回复
热议问题