Automapper and request specific resources

痴心易碎 提交于 2019-12-04 18:19:31

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

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

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);
    }
}

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

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

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

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...
});

Then the converter is:

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);
    }
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!