[英]Registering a different generic type as scanned
I try to register a generic type Repository<T>
with the interface IRepository<T>
where T
is IEntity
. 我尝试通过接口
IRepository<T>
注册通用类型Repository<T>
,其中T
是IEntity
。
builder.RegisterAssemblyTypes(assemblies)
.Where(t => typeof(IEntity).IsAssignableFrom(t))
.WithMetadata("Type", (t) => t)
.AsImplementedInterfaces()
.InstancePerLifetimeScope();
The question is now how to register for each IEntity
found my class 现在的问题是如何为找到我的课程的每个
IEntity
注册
Repository<T>: IRepository<T> where T: IEntity
Actually, you don't need to register the entities, you only have to register the repository. 实际上,您不需要注册实体,只需要注册存储库。 Autofac have excellent support for generics, both open and closed types.
Autofac对开放式和封闭式泛型都有出色的支持。 From the OpenGenerics documentation, register the open generic type of your repository:
从OpenGenerics文档中,注册存储库的开放通用类型:
builder.RegisterGeneric(typeof(Repository<>))
.As(typeof(IRepository<>));
You can now resolve closed repository types like this: 现在,您可以解析封闭的存储库类型,如下所示:
var userRepo = container.Resolve<IRepository<User>>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.