Specifying a default Unity type mapping for a generic interface and class pair

泪湿孤枕 提交于 2019-11-29 22:10:04

问题


We're using constructor-based dependency injection, AutoMapper and Unity on a codebase.

We have wrapped AutoMapper with a generic 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 it means that for every mapping we define in the AutoMapper configuration we need to perform an additional UnityContainer.RegisterType.

These type mappings are almost always of the form

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

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


回答1:


We actually do almost the same exact thing. In Unity, you can say:

unityContainer.RegisterType(typeof(IMapper<,>), typeof(AutomaticMapper<,>));



回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/2198982/specifying-a-default-unity-type-mapping-for-a-generic-interface-and-class-pair

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!