通过依赖注入解析控制器 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>();
}