gpt4 book ai didi

c# - 如何在 AutoMapper 配置文件类中注入(inject)服务?

转载 作者:太空宇宙 更新时间:2023-11-03 22:54:19 26 4
gpt4 key购买 nike

我正在做一个项目,我们有一个包含所有映射的 AutoMapper Profile 类。但是,出于某种原因,我需要调用一些服务,为了调用该服务,我需要在 Profile 类中调用注入(inject)该服务。

所以我的类(class)如下所示:

public class MyClass : Profile
{

public MyClass
{
//somemapping here
}

}

现在,假设我想注入(inject)一个服务,它需要在构造函数中获取该服务,构造函数如下所示:

public MyClass(IService service)
{
//somemapping here
}

现在,目前

services.AddAutoMapper();

调用所有继承自配置文件类的类神奇地自动,并且不调用参数构造函数。

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

最佳答案

您不能将依赖项注入(inject)到 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
}
}

然后在配置文件类中:

public class SomeProfile : Profile
{
public SomeProfile()
{
CreateMap<SomeModel, SomeOtherModel>()
.AfterMap<SetSomeAction>();
}
}

关于c# - 如何在 AutoMapper 配置文件类中注入(inject)服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46165652/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com