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 配置文件类中调用服务的最佳方式是什么?
您可以\xe2\x80\x99t 将依赖项注入到Profile
类中,但可以在IMappingAction
实现中执行此操作。
首先将AutoMapper.Extensions.Microsoft.DependencyInjection
包添加到您的项目中。然后创建一个IMappingAction
像这样的类:
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然后在配置文件类中:
\npublic 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
归档时间: |
|
查看次数: |
8352 次 |
最近记录: |