Automapper and request specific resources

北慕城南 提交于 2020-01-01 19:42:11

问题


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.

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

回答1:


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.



来源:https://stackoverflow.com/questions/6102359/automapper-and-request-specific-resources

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