I want to be able to resolve a collection of services from Autofac that represents all registered types which implement an open generic interface.
public interface IEntityService<in T> where T : Entity
{
void DoEntityWork(T entity);
}
I have many classes that inherit Entity and many corresponding service classes which implement IEntityService for that Entity.
public class EntityA : Entity { }
public class EntityB : Entity { }
public class EntityC : Entity { }
public class EntityAService : IEntityService<EntityA>
{
public void DoEntityWork(EntityA entity)
}
public class EntityBService : IEntityService<EntityB>
{
public void DoEntityWork(EntityB entity)
}
public class EntityCService : IEntityService<EntityC>
{
public void DoEntityWork(EntityB entity)
}
Here is how I am registering them with Autofac:
builder.RegisterType<EntityAService>().As<IEntityService<EntityA>();
builder.RegisterType<EntityBService>().As<IEntityService<EntityB>();
builder.RegisterType<EntityCService>().As<IEntityService<EntityC>();
What I would like to be able to do is to resolve each one of those IEntityService registrations in a collection. However, attempting to inject them with the following code returns an empty collection:
public class MyProcessingClass(IEnumerable<IEntityService<Entity>> entityServices)
{
_entityServices = entityServices;
}
I have tried instead registering them all As<IEntityService<Entity>>(), but this throws an ArgumentException with the following message:
The type 'MyProject.Services.EntityAService' is not assignable to service 'MyProject.Interfaces.IEntityService'1[[MyProject.Models.Entity]]
How can I resolve all of the types which implement IEntityService with a type argument that implements Entity?