自动映射并请求特定资源 [英] Automapper and request specific resources

查看:95
本文介绍了自动映射并请求特定资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑为我正在编写的ASP MVC Intranet应用程序使用自动映射器.我的控制器当前是使用Unity依赖项注入创建的,每个容器都获得该请求所独有的依赖项.

I'm considering automapper for an asp mvc intranet app I am writing. My controllers are currently created using Unity dependency injection, where each container gets dependencies unique to the request.

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

I need to know if automapper can be made to use a request specific resource ICountryRepository to look up an object, like so....

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

推荐答案

此处的选项对.一种是做一个自定义解析器:

Couple of options here. One is to do a custom resolver:

.ForMember(dest => dest.Country, opt => opt.ResolveUsing<CountryCodeResolver>())

那么您的解析器将是(假设CountryCode是一个字符串.可以是一个字符串,无论如何):

Then your resolver would be (assuming CountryCode is a string. Could be a string, whatever):

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:

Finally, you'll need to hook in Unity to AutoMapper:

Mapper.Initialize(cfg => {
    cfg.ConstructServicesUsing(type => myUnityContainer.Resolve(type));

    // Other AutoMapper configuration here...
});

其中"myUnityContainer"是您配置的Unity容器.定制解析程序定义一个成员与另一个成员之间的映射.我们通常为所有字符串->国家/地区映射定义一个全局类型转换器,因此我不需要配置每个成员.看起来像这样:

Where "myUnityContainer" is your configured Unity container. A custom resolver defines a mapping between one member and another. We often define a global type converter for all string -> Country mappings, so that I don't need to configure every single member. It looks like this:

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看到一个字符串->国家(地区)转换时,它都会使用上面的类型转换器.

In a custom type converter, you wouldn't need to do any member-specific mapping. Any time AutoMapper sees a string -> Country conversion, it uses the above type converter.

这篇关于自动映射并请求特定资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆