我正在做一个项目,其中我们有一个AutoMapper配置文件类,它具有所有的映射。但是,出于某种原因,我需要调用一些服务,为了调用该服务,我需要在Profile
类中调用inject服务。
所以我的课看起来如下:
public class MyClass : Profile
{
public MyClass
{
//somemapping here
}
}
现在,假设我想注入一个服务,它需要在构造函数中接受该服务,构造函数看起来如下所示:
public MyClass(IService service)
{
//somemapping here
}
现在,目前
services.AddAutoMapper();
调用从profile类auto magically
继承的所有类,并且它不调用参数构造函数。
现在我的问题是,在Automapper类中调用服务的最佳方法是什么?
发布于 2017-09-12 00:26:45
AddAutoMapper()
延拓法只是合成糖。根据您的需要,您始终可以手动初始化Automapper:
Mapper.Initialize(cfg => {
cfg.AddProfile(new MyClass());
});
https://github.com/AutoMapper/AutoMapper/wiki/Configuration#assembly-scanning-for-auto-configuration
也许这能解决你的问题。
发布于 2021-04-12 15:36:14
不能将依赖项注入Profile
类,但可以在IMappingAction
实现中进行。
首先,将AutoMapper.Extensions.Microsoft.DependencyInjection
包添加到项目中。然后创建如下所示的IMappingAction
类:
public class SetSomeAction : IMappingAction<SomeModel, SomeOtherModel>
{
private readonly IService service;
public SetSomeAction(IService _service)
{
service = _service;
}
public void Process(SomeModel source, SomeOtherModel destination, ResolutionContext context)
{
//here you use the service and change destination
}
}
然后在profile类中:
public class SomeProfile : Profile
{
public SomeProfile()
{
CreateMap<SomeModel, SomeOtherModel>()
.AfterMap<SetSomeAction>();
}
}
https://stackoverflow.com/questions/46165652
复制相似问题