Roman Roman - 15 days ago 7
C# Question

How to register all implementations of Generic interface in autofac?

I have created generic interface that suppose to map entities to view models and backwards. I have to make around 80 registrations in autofac configuration. Is it possible to register them as batch?
Here is the interface:

public interface ICommonMapper<TEntity, TModel, TKey>
where TEntity : BaseEntity<TKey>
where TModel : BaseEntityViewModel<TKey>
where TKey : struct
{
TModel MapEntityToModel(TEntity entity);
TModel MapEntityToModel(TEntity entity, TModel model);
TEntity MapModelToEntity(TModel model);
TEntity MapModelToEntity(TModel model, TEntity entity);
}


Thanks!

Answer

You could use :

builder.RegisterAssemblyTypes(assemblies)
       .AsClosedTypesOf(typeof(ICommonMapper<,,>));

Where assemblies is a collection of the assemblies where your types belong.

if you have a PersonMapper that inherits from ICommonMapper<Person, PersonModel, Int32>, Autofac will be able to resolve ICommonMapper<Person, PersonModel, Int32>

Comments