[英]Registration of open generic types - type parameter mismatch
我正在尝试按如下方式注册我的通用存储库的所有实现:
container.Register(typeof(IRepository<>), new[] { typeof(Repository<>).Assembly });
但是,容器无法验证我的配置:
附加信息:配置无效。 为类型 IErrorLogService 创建实例失败。 ErrorLogService 类型的构造函数包含名称为“errorLogRepository”且类型为 IRepository<ErrorLog> 的未注册参数。 请确保 IRepository<ErrorLog> 已注册,或更改 ErrorLogService 的构造函数。 请注意,存在不同类型 Persistence.Interfaces.Repository.Generic.IRepository<T> 的注册,而请求的类型为 Persistence.Interfaces.Repository.Generic.IRepository<Persistence.DataModel.ErrorLog>。
基于各种 SO 线程,上面的代码片段应该是要走的路。 我错过了什么?
我的存储库类:
public class Repository<T> : IRepository<T> where T : Entity { }
IRepository
和Repository
存在于同一个程序集中。
每种类型的显式注册都有效:
container.Register<IRepository<ErrorLog>, Repository<ErrorLog>>();
您在其文档中使用状态的Register(Type openGenericServiceType, IEnumerable<Assembly> assemblies)
重载:
在给定的
assemblies
集中注册所有具体的、非泛型的、公共的和内部类型,这些assemblies
使用容器的默认生活方式(默认情况下是瞬态的)实现给定的openGenericServiceType
。
请注意此处的“非通用”一词。 此注册重载旨在批量注册开放通用服务类型的所有非通用实现。 由于您有一个开放的通用实现,因此该Register
方法将找不到它。
相反,您应该使用Register(Type serviceType, Type implementationType)
重载,它指出:
注册每次请求
serviceType
时将返回的新实例。 如果serviceType
和implementationType
表示相同的类型,则该类型自行注册。 支持开放和封闭的泛型类型。
TLDR;
将您的注册更改为以下内容:
container.Register(typeof(IRepository<>), typeof(Repository<>));
您可以在Simple Injector 的文档中找到更多相关信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.