【问题标题】:How to inject a service in AutoMapper Profile class?如何在 AutoMapper Profile 类中注入服务?
【发布时间】:2017-09-11 23:24:17
【问题描述】:

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

所以我的班级如下所示:

public class MyClass : Profile
{

public MyClass
{
   //somemapping here
}

}

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

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

现在,现在

services.AddAutoMapper();

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

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

【问题讨论】:

标签: c# .net-core automapper


【解决方案1】:

AddAutoMapper() 扩展方法只是合成糖。 根据您的需要,您可以随时手动初始化 Automapper:

Mapper.Initialize(cfg => {
   cfg.AddProfile(new MyClass());
});

https://github.com/AutoMapper/AutoMapper/wiki/Configuration#assembly-scanning-for-auto-configuration

也许这能解决你的问题。

【讨论】:

  • 但是通过这种方法,配置文件类中没有依赖注入,如果你在不同的地方有很多配置文件,你不需要到处都做一个 Mapper.Initialize(),它AutoMapper Dependecy Injection 试图解决的问题。
  • 您是在问是否可以在构建配置文件类时使用 DI?你,只需使用你的依赖容器传递你的类:cfg.AddProfile(new MyClass(provider.GetService<IService>()))
【解决方案2】:

您不能将依赖项注入Profile 类,但可以在IMappingAction 实现中进行。

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

public class SetSomeAction : IMappingAction<SomeModel, SomeOtherModel>
{
    private readonly IService service;

    public SetTraceIdentifierAction(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>();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-01
    • 2019-06-21
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多