Specifying default Unity type mappings for a common interface and a pair of classes

We use dependency injection based on constructor, AutoMapper and code based Unity .

We wrapped AutoMapper using a common interface ...

public interface IMapper<TSource, TDestination> { TDestination Map(TSource source); } 

And a class that implements this interface ...

 public class AutomaticMapper<TSource, TDestination> : IMapper<TSource, TDestination> { public TDestination Map(TSource source) { return AutoMapper.Mapper.Map<TSource, TDestination>(source); } } 

This works well, but that means that for each display that we define in the AutoMapper configuration, we need to run an additional UnityContainer.RegisterType .

These type mappings almost always have the form

 container.RegisterType<IMapper<ClassA, ClassB>, AutomaticMapper<ClassA, ClassB>>(); 

Is there a way to show unity to use the default type mapping that maps from IMapper to AutomaticMapper using the same TSource and TDestination for each of them?

+4
source share
3 answers

In fact, we are doing almost the same thing. In Unity, you can say:

 unityContainer.RegisterType(typeof(IMapper<,>), typeof(AutomaticMapper<,>)); 
+9
source
 public class AutomaticMapper : IMapper { public TDestination Map<TSource, TDestination>(TSource source) { return AutoMapper.Mapper.Map<TSource, TDestination>(source); } } 
+1
source

There's a registration add-in for Unity that probably does what you want. Take a look at http://unity.codeplex.com/Thread/View.aspx?ThreadId=59418

+1
source

Source: https://habr.com/ru/post/1300281/


All Articles