我正在考虑为我正在编写的 asp mvc Intranet 应用程序使用自动映射器。我的 Controller 当前是使用 Unity 依赖项注入(inject)创建的,其中每个容器获取请求所独有的依赖项。
我需要知道是否可以使自动映射器使用请求特定资源 ICountryRepository 来查找对象,就像这样......
domainObject.Country = CountryRepository.Load(viewModelObject.CountryCode);
最佳答案
这里有几个选项。一种是做一个自定义解析器:
.ForMember(dest => dest.Country, opt => opt.ResolveUsing<CountryCodeResolver>())
那么你的解析器将是(假设 CountryCode 是一个字符串。可以是一个字符串,无论如何):
public class CountryCodeResolver : ValueResolver<string, Country> {
private readonly ICountryRepository _repository;
public CountryCodeResolver(ICountryRepository repository) {
_repository = repository;
}
protected override Country ResolveCore(string source) {
return _repository.Load(source);
}
}
最后,您需要将 Unity 连接到 AutoMapper:
Mapper.Initialize(cfg => {
cfg.ConstructServicesUsing(type => myUnityContainer.Resolve(type));
// Other AutoMapper configuration here...
});
其中“myUnityContainer”是您配置的 Unity 容器。自定义解析器定义一个成员与另一个成员之间的映射。我们经常为所有字符串 -> 国家/地区映射定义一个全局类型转换器,这样我就不需要配置每个成员。它看起来像这样:
Mapper.Initialize(cfg => {
cfg.ConstructServicesUsing(type => myUnityContainer.Resolve(type));
cfg.CreateMap<string, Country>().ConvertUsing<StringToCountryConverter>();
// Other AutoMapper configuration here...
});
那么转换器是:
public class StringToCountryConverter : TypeConverter<string, Country> {
private readonly ICountryRepository _repository;
public CountryCodeResolver(ICountryRepository repository) {
_repository = repository;
}
protected override Country ConvertCore(string source) {
return _repository.Load(source);
}
}
在自定义类型转换器中,您不需要执行任何特定于成员的映射。任何时候 AutoMapper 看到字符串 -> 国家/地区转换,它都会使用上面的类型转换器。
关于unity-container - 自动映射并请求特定资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6102359/