unity-container - 自动映射并请求特定资源

标签 unity-container automapper

我正在考虑为我正在编写的 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/

相关文章:

c# - 使用自动映射器映射异步结果

c# - 如何处理 Automapper 异常(try/catch)

c# - AutoMapper map 中 foreach 的额外迭代

c# - WCF、Unity、EntLib5、Linq-to-SQL 与 TDD 和 PI 的示例

unity-container - 拆分统一配置文件

c# - Unity 和 TransientLifetimeManager

c# - Unity 5.9.x 中缺少 CreateChildContainer

c# - AutoMapper 枚举字节类型初始化异常

c# - 使用 AutoMapper 映射 "LinkedList"

c# - 如何让 Unity 解析 AutoMapper 在映射时创建的模型?