如何在 ASP.NET Core 3.0 中的另一个程序集中使用控制器?

ibe*_*dev 6 asp.net-mvc asp.net-core-3.0

默认的 dotnet core 3 web api 模板假定控制器与 Startup.cs

如何让它知道不同程序集中的控制器?

我个人喜欢让我的解决方案更有层次,并且只取决于它需要依赖的东西

MyApp.Host --> MyApp.WebApi --> MyApp.Application --> MyApp.Domain
Run Code Online (Sandbox Code Playgroud)

因此,MyApp.Host我不希望对 MVC 框架有任何直接依赖(尽管我知道在 Dotnet Core 3 中这已经是隐式的)。控制器在MyApp.WebApi

ibe*_*dev 7

解决方案是.AddApplicationPart(assembly)Startup.cs.

因此,如果我有一个 MyApp.WebApi依赖于 nuGet 包的项目:(Microsoft.AspNetCore.Mvc.Core当前版本为 2.2.5)具有以下控制器:

using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace MyApp.WebApi.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class SamplesController 
        : ControllerBase
    {
        [HttpGet]
        public IEnumerable<string> Get()
        {
            var samples =
                new List<string>
                {
                    "sample1", "sample2", "sample3"
                };

            return samples;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Startup.csMyApp.Host身份是:

using MyApp.WebApi.Controllers;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Reflection;

namespace MyApp.Cmd.Host
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            var sampleAssembly = Assembly.GetAssembly(typeof(SamplesController));
            services
                .AddControllers()
                .AddApplicationPart(sampleAssembly)
                .AddControllersAsServices();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

Run Code Online (Sandbox Code Playgroud)

然后应用程序将检测不同程序集中的控制器,我将能够访问: https://localhost:5001/samples

  • 我还不知道为什么没有 MVC 3.0 (2认同)