如何在 AutoMapper Profile 类中注入服务?

Los*_*ost 2 c# automapper .net-core

我正在开发一个项目,其中我们有 AutoMapper Profile 类,其中包含所有映射。但是,由于某种原因,我需要调用某些服务,并且为了调用该服务,我需要在Profile类中调用注入该服务。

所以我的课程如下所示:

public class MyClass : Profile
{

public MyClass
{
   //somemapping here
}

}
Run Code Online (Sandbox Code Playgroud)

现在,假设我想注入一个服务,它需要在构造函数中使用该服务,构造函数如下所示:

public MyClass(IService service)
    {
       //somemapping here
    }
Run Code Online (Sandbox Code Playgroud)

现在,目前

services.AddAutoMapper();
Run Code Online (Sandbox Code Playgroud)

调用所有继承自 profile class 的类auto magically,并且不调用参数构造函数。

现在我的问题是在 Automapper 配置文件类中调用服务的最佳方式是什么?

Moj*_*aba 5

您可以\xe2\x80\x99t 将依赖项注入到Profile类中,但可以在IMappingAction实现中执行此操作。

\n

首先将AutoMapper.Extensions.Microsoft.DependencyInjection包添加到您的项目中。然后创建一个IMappingAction像这样的类:

\n
public class SetSomeAction : IMappingAction<SomeModel, SomeOtherModel>\n{\n    private readonly IService service;\n\n    public SetSomeAction(IService _service)\n    {\n        service = _service;\n    }\n\n    public void Process(SomeModel source, SomeOtherModel destination, ResolutionContext context)\n    {\n        //here you use the service and change destination\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

然后在配置文件类中:

\n
public class SomeProfile : Profile\n{\n    public SomeProfile()\n    {\n        CreateMap<SomeModel, SomeOtherModel>()\n            .AfterMap<SetSomeAction>();\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n