Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register all implementations of Generic interface in autofac?

Tags:

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!

like image 358
Roman Avatar asked Jun 08 '16 16:06

Roman


People also ask

How do I register a generic repository in Autofac?

You need to exactly write like this: builder. RegisterGeneric(typeof(RepositoryBase<>)) . As(typeof(IRepository<>)); note the empty <> and it will register your Repository for all of your entites.

How do I register an Autofac interface?

Register by Type var builder = new ContainerBuilder(); builder. RegisterType<ConsoleLogger>(); builder. RegisterType(typeof(ConfigReader)); When using reflection-based components, Autofac automatically uses the constructor for your class with the most parameters that are able to be obtained from the container.


1 Answers

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>

like image 57
Cyril Durand Avatar answered Sep 30 '22 21:09

Cyril Durand