Nie*_*ksa 3 c# autofac asp.net-core-2.0
我正在尝试使用 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;
}
}
Run Code Online (Sandbox Code Playgroud)
如上所示,我遵循了 Autofac 的文档。不幸的是 LoginController 不会被构造,因为它需要注入。
编辑:如果有一种不使用 Autofac 使用“模块”的方法,我会对任何建议非常感兴趣:)
提前谢谢你!
默认情况下,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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16742 次 |
| 最近记录: |