简体   繁体   中英

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 .

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

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. From the OpenGenerics documentation, register the open generic type of your repository:

builder.RegisterGeneric(typeof(Repository<>))
    .As(typeof(IRepository<>));

You can now resolve closed repository types like this:

var userRepo = container.Resolve<IRepository<User>>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM