-->

Automapper and request specific resources

2020-07-30 02:36发布

问题:

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.