通過依賴注入解析控制器 ViewComponents 和 TagHelpers

預設情況下,Controllers,ViewComponents 和 TagHelper 未通過依賴項注入容器進行註冊和解析。這導致在使用第三方 Inversion of Control(IoC) 容器(如 AutoFac)時無法進行屬性注入。

為了使 ASP.NET Core MVC 也通過 IoC 解決這些型別,需要在 Startup.cs 中新增以下注冊(取自 GitHub 上的官方 ControllersFromService 示例

public void ConfigureServices(IServiceCollection services)
{
    var builder = services
        .AddMvc()
        .ConfigureApplicationPartManager(manager => manager.ApplicationParts.Clear())
        .AddApplicationPart(typeof(TimeScheduleController).GetTypeInfo().Assembly)
        .ConfigureApplicationPartManager(manager =>
        {
            manager.ApplicationParts.Add(new TypesPart(
              typeof(AnotherController),
              typeof(ComponentFromServicesViewComponent),
              typeof(InServicesTagHelper)));

            manager.FeatureProviders.Add(new AssemblyMetadataReferenceFeatureProvider());
        })
        .AddControllersAsServices()
        .AddViewComponentsAsServices()
        .AddTagHelpersAsServices();

    services.AddTransient<QueryValueService>();
    services.AddTransient<ValueService>();
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}