为通用接口和类对指定默认的Unity类型映射 [英] Specifying a default Unity type mapping for a generic interface and class pair
问题描述
我们正在使用基于构造函数的依赖注入, AutoMapper 和 Unity 代码库。
We're using constructor-based dependency injection, AutoMapper and Unity on a codebase.
我们用一个通用接口封装了AutoMapper .. 。
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);
}
}
这个效果很好,但这意味着对于每个映射我们在AutoMapper配置中定义,我们需要执行一个额外的 UnityContainer.RegisterType
。
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>>();
有什么办法可以让团队使用从<$ c映射的默认类型映射$ c> IMapper to AutomaticMapper
使用相同的 TSource
和
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?
推荐答案
我们实际上做的几乎相同。在Unity中,您可以说:
We actually do almost the same exact thing. In Unity, you can say:
unityContainer.RegisterType(typeof(IMapper<,>), typeof(AutomaticMapper<,>));
这篇关于为通用接口和类对指定默认的Unity类型映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!