首页 > 解决方案 > 如何在 ASP.NET Core 3.0 的另一个程序集中使用控制器?

问题描述

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

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

我个人喜欢让我的解决方案更加分层,并且只取决于它需要依赖的内容

MyApp.Host --> MyApp.WebApi --> MyApp.Application --> MyApp.Domain

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

标签: asp.net-mvcasp.net-core-3.0

解决方案


解决方案是.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;
        }
    }
}

我有我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();
            });
        }
    }
}

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


推荐阅读