3

我想注册具有多个构造函数的程序集类型自动装配选择了错误的构造函数并希望像在 RegisterType 中那样指定它

builder.RegisterType(typeof(IController))
    .UsingConstructor(typeof(IUnitOfWork));

但是当我这样做时

builder.RegisterAssemblyTypes(typeof(IController).Assembly)
    .UsingConstructor(typeof(IUnitOfWork));

我明白了

“'System.Object' 类型上不存在匹配的构造函数。”

我认为这是因为装配类型比我想象的要复杂一些,但问题仍然存在

我该怎么办?

4

1 回答 1

7

通过做

builder.RegisterType(typeof(IController))
       .UsingConstructor(typeof(IUnitOfWork));

您在Autofac容器中注册 IController并告诉它应该使用带IUnitOfWork参数的构造函数。

UsingConstructor方法不起作用,RegisterAssemblyTypes但在您的情况下,您可以使用FindConstructorWith方法。

builder.RegisterAssemblyTypes(typeof(IController).Assembly)
       .FindConstructorsWith(t => new[] { 
           t.GetConstructor(new[] { typeof(IUnitOfWork) }) 
       })
       .As<IController>();
于 2015-05-19T21:09:23.777 回答