Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 750
Kenci Avatar asked Apr 21 '16 21:04

Kenci


2 Answers

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

like image 109
MaKCbIMKo Avatar answered Sep 17 '22 23:09

MaKCbIMKo


You can register it like so:

container.RegisterType<IMappingEngine>(new InjectionFactory(_ => Mapper.Engine));

Then you can inject it as IMappingEngine.

private IMappingEngine_mapper;
public RssLocalRepository(IMappingEnginemapper)
{
    _mapper = mapper;
}

More information found here:

https://kalcik.net/2014/08/13/automatic-registration-of-automapper-profiles-with-the-unity-dependency-injection-container/

like image 39
smoksnes Avatar answered Sep 17 '22 23:09

smoksnes