我正在尝试用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的“模块”,我会非常有趣的任何建议:)
提前谢谢你!
解决方法:
在ASP.NET Core中使用InstancePerLifetimeScope. differences between ASP.NET and ASP.NET Core like this are documented.