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?
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
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With