How to register an AutoMapper profile with Unity

試著忘記壹切 提交于 2019-12-10 15:27:06

问题


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?


回答1:


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




回答2:


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/



来源:https://stackoverflow.com/questions/36780573/how-to-register-an-automapper-profile-with-unity

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