在需要时让AutoMapper使用IoC容器注入依赖项 [英] Having AutoMapper to inject dependencies using an IoC Container when needed
问题描述
我几乎已经尝试了所有方法,但是当B没有无参数构造函数时,我无法让AutoMapper映射A => B.
我正在使用Unity,所有的依赖项都可以方便地注册,但是,我如何对AutoMapper说:嘿,如果目标实例在构造函数中需要一些依赖项,请Unity进行构建,然后再进行映射./p>
我尝试过
Mapper.Initialize(configuration =>
{
configuration.ConstructServicesUsing(container.Resolve);
configuration.CreateMap<Person, PersonViewModel>();
});
但是它不起作用:(
实际上,我撒了谎.我没有使用Unity.我正在使用 Grace ,但不想提出一个相对未知的容器来询问高级主题:)
我已经解决了这个问题,它像丝绸一样光滑.确切的代码是这样的.请记住,我正在使用Grace IoC容器(我强烈建议使用).
Bootstrapper.Instance.Configure(new CompositionRoot());
Mapper.Configuration.ConstructServicesUsing(type => Bootstrapper.Instance.Container.Locate(type));
Mapper.CreateMap<Person, PersonViewModel>()
.ConstructUsingServiceLocator();
像这样:
configuration.CreateMap<Person, PersonViewModel>()
.ConstructUsingServiceLocator();
对应该由服务定位器创建的每个映射执行此操作.
I have tried almost everything, but I cannot get AutoMapper to map A => B when B doesn't have a parameterless constructor.
I'm using Unity and all the dependencies are registered conveniently but, how do I say to AutoMapper "hey, if the target instance needs some dependency in the constructor, ask Unity to build it, and do the mapping later.
I've tried with
Mapper.Initialize(configuration =>
{
configuration.ConstructServicesUsing(container.Resolve);
configuration.CreateMap<Person, PersonViewModel>();
});
But it doesn't work :(
EDIT: In fact, I lied a bit. I'm not using Unity. I'm using Grace, but didn't want to come up with a relatively unknown container asking about advances topics :)
I've solved the problem and it works as smooth as silk. The exact code is like this. Keep in mind that I'm using the Grace IoC Container (which I eagerly recommend).
Bootstrapper.Instance.Configure(new CompositionRoot());
Mapper.Configuration.ConstructServicesUsing(type => Bootstrapper.Instance.Container.Locate(type));
Mapper.CreateMap<Person, PersonViewModel>()
.ConstructUsingServiceLocator();
Like this:
configuration.CreateMap<Person, PersonViewModel>()
.ConstructUsingServiceLocator();
Do this for each mapping that should be created by your service locator.
这篇关于在需要时让AutoMapper使用IoC容器注入依赖项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!