Dec*_*lty 6 dependency-injection inversion-of-control autofac .net-core asp.net-core
我有一个 .Net Core 2 应用程序和一个继承自抽象基类的 API 控制器类:
[Route("api/[controller]")]
public class MyController : BaseController
Run Code Online (Sandbox Code Playgroud)
在基本控制器上,我有:
public ICommandProcessor CommandProcessor { get; set; }
Run Code Online (Sandbox Code Playgroud)
在我的 StartUp.cs 中,我有:
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.Where(t => t.IsSubclassOf(typeof(BaseController)))
.PropertiesAutowired();
Run Code Online (Sandbox Code Playgroud)
但是,CommandProcessor 属性始终为空。我尝试将它移到派生类并尝试直接注册类型,如下所示:
builder.RegisterType<MyController>().PropertiesAutowired();
Run Code Online (Sandbox Code Playgroud)
还有基类:
builder.RegisterType<BaseController>().PropertiesAutowired();
Run Code Online (Sandbox Code Playgroud)
我已经尝试了此处和此处以及其他帖子中的建议,但似乎没有任何效果,这让我认为这是 .Net Core 2 中的一个问题。
当我将 ICommandProcessor 注入控制器构造函数时,它连接良好。
值得一提的是,我在其他不是控制器的类上也试过这个,在启动时按如下方式注册:
builder.RegisterType<DomainEvents>().PropertiesAutowired();
Run Code Online (Sandbox Code Playgroud)
并且该属性也仍然为空。
编辑:
我在 github 上的 autofac 项目页面上提出了这个问题,他们建议我展示完整的 ConfigureServices 类,如下所示:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc().AddControllersAsServices();
// Identity server
var builder = new ContainerBuilder();
builder.RegisterModule(new CoreImplementationModule());
builder.RegisterModule(new PortalCoreImplementationModule());
builder.Register((context, _) => new DocumentClient(
new Uri(Configuration["DocumentDb:Uri"]),
Configuration["DocumentDb:Key"],
null,
new ConsistencyLevel?()))
.As<IDocumentClient>();
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.Where(t => t.IsSubclassOf(typeof(BaseController)))
.PropertiesAutowired();
builder.Populate(services);
builder.RegisterType<DomainEvents>().PropertiesAutowired();
var container = builder.Build();
return new AutofacServiceProvider(container);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
788 次 |
| 最近记录: |