【问题标题】:Automapper and request specific resourcesAutomapper 并请求特定资源
【发布时间】:2011-05-23 20:02:51
【问题描述】:

我正在考虑为我正在编写的 asp mvc Intranet 应用程序使用 automapper。我的控制器目前是使用 Unity 依赖注入创建的,其中每个容器都获取请求唯一的依赖项。

我需要知道是否可以使自动映射器使用请求特定的资源 ICountryRepository 来查找对象,就像这样......

domainObject.Country = CountryRepository.Load(viewModelObject.CountryCode);

【问题讨论】:

    标签: unity-container automapper


    【解决方案1】:

    这里有几个选项。一种是做一个自定义解析器:

    .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 容器。自定义解析器定义一个成员和另一个成员之间的映射。我们经常为所有 string -> Country 映射定义一个全局类型转换器,这样我就不需要配置每个成员。它看起来像这样:

    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 看到一个字符串 -> Country 转换,它都会使用上面的类型转换器。

    【讨论】:

    • 感谢您提供翔实的回答!不幸的是,在配置自动映射器时我不会引用容器,因为容器将是主容器在收到请求时创建的子容器。
    猜你喜欢
    • 2018-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 2012-11-13
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多