c# - 使用 UsingConstructor 注册 AssemblyTypes

标签 c# autofac

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

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

但是当我这样做的时候

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

我明白了

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

我认为这是因为程序集类型比我想象的要复杂一些,但问题仍然悬而未决

我该怎么办?

最佳答案

通过做

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>();

关于c# - 使用 UsingConstructor 注册 AssemblyTypes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12782680/

相关文章:

c# - UWP 中的数据绑定(bind)到嵌套集合

c# - 获取警告 "The source expression is always of pattern' s 类型,匹配所有非空值”

c# - 用户控件、自定义控件和组件之间有什么区别?

c# - 在手动调整尺寸之前,窗口无法最大化

c# - Autofac 中的装饰器和属性注入(inject)

asp.net - Ioc 和 WebForms - 如何在用户控件中注入(inject)属性

c# - 使用错误的 readasstringasync 调用 ContinueWith

c# - 使用 AutoFac 的 MVC Controller 通用注入(inject)

asp.net-mvc-3 - 使用 Autofac 将属性注入(inject)到自定义 WebViewPage

asp.net-mvc - 如何在不使用 Controller 基类的情况下为所有 View 设置 ViewBag 属性?