我想注册具有多个构造函数的程序集类型自动装配选择错误的构造函数并希望像在RegisterType中一样指定它
builder.RegisterType(typeof(IController))
.UsingConstructor(typeof(IUnitOfWork));
Run Code Online (Sandbox Code Playgroud)
但是当我这样做的时候
builder.RegisterAssemblyTypes(typeof(IController).Assembly)
.UsingConstructor(typeof(IUnitOfWork));
Run Code Online (Sandbox Code Playgroud)
我明白了
"类型'System.Object'上不存在匹配的构造函数."
我认为这是因为装配类型比我想象的要复杂一点,但问题仍然存在
我该怎么办?
通过做
builder.RegisterType(typeof(IController))
.UsingConstructor(typeof(IUnitOfWork));
Run Code Online (Sandbox Code Playgroud)
您在Autofac容器中注册IController 并告诉它应该使用带IUnitOfWork参数的构造函数.
该UsingConstructor方法不起作用,RegisterAssemblyTypes但在您的情况下,您可以使用FindConstructorWith方法.
builder.RegisterAssemblyTypes(typeof(IController).Assembly)
.FindConstructorsWith(t => new[] {
t.GetConstructor(new[] { typeof(IUnitOfWork) })
})
.As<IController>();
Run Code Online (Sandbox Code Playgroud)