ASP.NET Core 2.0 使用 Autofac 注入控制器

ASP.NET Core 2.0 inject Controller with Autofac

我正在尝试用 Autofac 注入我的控制器。不幸的是,我无法配置 Autofac,因此“DefaultControllerActivator”不会构建我的控制器?

    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().AddControllersAsServices();
        var containerBuilder = new ContainerBuilder();
        containerBuilder.RegisterModule<ServiceModule>();
        containerBuilder.Populate(services);
        containerBuilder.RegisterType<LoginController>().PropertiesAutowired();

        ApplicationContainer = containerBuilder.Build();
        return new AutofacServiceProvider(this.ApplicationContainer);
    }

    public class ServiceModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterModule(new DataProviderModule());
            builder.RegisterType(typeof(LoginService)).As(typeof(ILoginService)).InstancePerRequest();
        }
    }

    [Route("api/[controller]")]
    public class LoginController : Controller
    {
        private readonly ILoginService _loginService;

        public LoginController(ILoginService loginService)
        {
            _loginService = loginService;
        }
    }

我按照上面显示的 Autofac 文档进行操作。不幸的是,LoginController 将不会被构建,因为它需要注入。

编辑:如果有一种不用 Autofac 使用 "Modules" 的方法,我会很乐意提供任何建议:)

提前致谢!

在 ASP.NET 核心中使用 InstancePerLifetimeScopedifferences between ASP.NET and ASP.NET Core like this are documented.

默认情况下,ASP.NET Core 将从容器中解析控制器参数,但实际上不会从容器中解析控制器。这通常不是问题,但它确实意味着:

控制器的生命周期由框架处理,而不是请求生命周期。

控制器构造函数参数的生命周期由请求生命周期处理。 您在控制器注册期间可能进行的特殊接线(例如设置 属性 注入)将不起作用。

您可以通过在向服务集合注册 MVC 时指定 AddControllersAsServices() 来更改此设置。这样做会在您调用 builder.Populate(services).

时自动将控制器类型注册到 IServiceCollection 中
public class Startup
{
  public IContainer ApplicationContainer {get; private set;}
  public IServiceProvider ConfigureServices(IServiceCollection services)
  {
    // Add controllers as services so they'll be resolved.
    services.AddMvc().AddControllersAsServices();

    var builder = new ContainerBuilder();

    // When you do service population, it will include your controller
    // types automatically.
    builder.Populate(services);

    // If you want to set up a controller for, say, property injection
    // you can override the controller registration after populating services.
    builder.RegisterType<MyController>().PropertiesAutowired();

    this.ApplicationContainer = builder.Build();
    return new AutofacServiceProvider(this.ApplicationContainer);
  }
}