我有一个.Net Core 2应用程序和一个继承自抽象基类的API控制器类:
[Route("api/[controller]")]
public class MyController : BaseController
在基础控制器上我有:
public ICommandProcessor CommandProcessor { get; set; }
在我的StartUp.cs中,我有:
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.Where(t => t.IsSubclassOf(typeof(BaseController)))
.PropertiesAutowired();
但是,CommandProcessor属性始终为null。我已经尝试将它移动到派生类并尝试直接注册类型,如下所示:
builder.RegisterType<MyController>().PropertiesAutowired();
以及基类:
builder.RegisterType<BaseController>().PropertiesAutowired();
我已尝试过此处和其他帖子中的建议,但似乎没有任何效果,这让我觉得它是.Net Core 2中的一个问题。
当我将ICommandProcessor注入控制器构造器时,它接线良好。
值得一提的是,我在其他不是控制器的类上试过这个,在启动时以下列方式注册:
builder.RegisterType<DomainEvents>().PropertiesAutowired();
并且该属性也仍然为空。
编辑:
我在github上的autofac项目页面上提出了this,他们建议我显示完整的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);
}