Question

I'm trying to configure my Object Mapper without knowing which mapper I'm using. :/

This might sound a bit strange. The reason for this is that I'm trying out the Onion Architecture so my UI cannot know about my Object Mapper located in my Infrastructure. See this solution for an example.

Onion Architecture

I'm having some trouble figuring out how I should "delegate" the none default mapping behavior. Stuff like:

Mapper
    .CreateMap<MyModel, MyDestViewModel>()
    .ForMember(
        dest => dest.SomeDestinationProperty,
        opt => opt.MapFrom(src => src.SomeSourceProperty)
    );

I've setup a class in my MVC project which is called from Global.asax and this is where I want to configure my mappings.

public static class MapConfig
{
    public static void RegisterMaps()
    {

    }
}

I was thinking I could do something like the following. (IMapper is a self defined interface located in Domain)

public static void RegisterMaps(HttpConfiguration config)
{
    var mapper = config.DependencyResolver.GetService(IMapper);
    mapper.CreateMap<MyModel, MyViewModel>();
}

Now... how would I go about setting up special behavior like the .ForMember? Keeping in mind that it cannot be AutoMapper specific.

I was thinking something along these lines mapper.CreateMap<MyModel, MyViewModel>(Expression<Func<T>>) where the Func would do some black magic that I cannot figure out right now :( - Am I on the right path or have I missed something essential?

Was it helpful?

Solution

Onion Architecture isn't about the configuration being implementation-agnostic, it's about the execution.

Just create an IMapper interface for the execution of mappings, but don't worry about the configuration. This applies to your ORM, IoC container and everything else.

Also, Onion Architecture isn't about project structure, it's about the direction of your dependencies. Just call CreateMap in your UI. You can then define an IMapper interface all the way down in Core, with the other pieces implementing a version that delegates to AutoMapper.

OTHER TIPS

you're abstracting away useful functionality that will cost you more time than you initially realize. Why not spend the time choosing a mapper and sticking with it?

Why is it so important that your UI doesnt know about your mapper? Assuming that you are using MVC, you are going to be flexing a lot of your chosen mappers functionality to flatten our your domain models to view models anyway.

Its the same kind of nonsense where people use generic repository implementations 'just in case' they decide to switch ORM mid project.

Choose your infrastructure carefully and stick with it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top