Search code examples
c#unity-containerautomapper

How to register an AutoMapper profile with Unity


I have the following AutoMapper profile:

public class AutoMapperBootstrap : Profile
{
    protected override void Configure()
    {
        CreateMap<Data.EntityFramework.RssFeed, IRssFeed>().ForMember(x => x.NewsArticles, opt => opt.MapFrom(y => y.RssFeedContent));
        CreateMap<IRssFeedContent, Data.EntityFramework.RssFeedContent>().ForMember(x => x.Id, opt => opt.Ignore());
    }
}

And I am initializing it like this:

var config = new MapperConfiguration(cfg =>
{
       cfg.AddProfile(new AutoMapperBootstrap());
});

container.RegisterInstance<IMapper>("Mapper", config.CreateMapper());

When I try to inject it in my constructor:

private IMapper _mapper;
public RssLocalRepository(IMapper mapper)
{
    _mapper = mapper;
}

I recieve the following error:

The current type, AutoMapper.IMapper, is an interface and cannot be constructed. Are you missing a type mapping?

How can I initialize the AutoMapper profile properly with Unity, so that I can use the mapper anywhere through DI?


Solution

  • In your example you are creating named mapping:

    // named mapping with "Mapper name"
    container.RegisterInstance<IMapper>("Mapper", config.CreateMapper());
    

    But how your resolver will know about this name?

    You need to register you mapping without name:

    // named mapping with "Mapper name"
    container.RegisterInstance<IMapper>(config.CreateMapper());
    

    It will map your mapper instance to IMapper interface and this instance will be returned on resolving interface