使用数据库在 .NET Core 控制台应用程序中配置 Automapper?

Configuring Automapper in a .NET Core Console App with a data library?

我对 AutoMapper、.NET Core 和 DI 非常陌生 - 尽管我熟悉 .NET Framework。我正在努力让 AutoMapper 在我构建的应用程序中工作。该应用程序是一个控制台应用程序,它附加了一个数据库。

我尝试在控制台应用程序的 Main() 方法中配置 AutoMapper - 因为据我了解,您需要在应用程序的启动点配置它?然后我在数据库中创建一个 class 的实例,然后数据库又创建一个 Mappers class 的实例,我在其中进行所有映射。我不确定我是否已正确设置所有内容,如果设置正确,我不确定要将什么传递给 Mappers class 中的构造函数以使其全部正常工作?

控制台:

class Program
{
    static void Main()
    {
        var services = new ServiceCollection();
        services.AddAutoMapper(typeof(AutoMapping));

        Learner learner = new Learner();            
    }
}

class AutoMapping : Profile
{
    public AutoMapping()
    {
        CreateMap<LearnerDTO, LearnerModel>();
    } 
}

学习者Class(在我的数据库中):

public class Learner
{
    public string GetLearner()
    {
        Mappers mappers = new Mappers(); //This Mappers instance is underlined red

        LearnerDTO learnerDTO = JsonFactory.LoadJson();
        LearnerModel learnerModel = mappers.LearnerDTOtoLearnerModel(learnerDTO);
        
    }

}

映射器Class:

public class Mappers
{
    private IMapper _mapper;

    public Mappers(IMapper mapper)
    {
        _mapper = mapper;
    }

    public LearnerModel LearnerDTOtoLearnerModel(LearnerDTO learnerDto)
    {
        LearnerModel model = _mapper.Map<LearnerModel>(learnerDto);

        return model;
    }
}

首先,我想评论一下我是否在正确的地方正确配置了 AutoMapper?其次,如果一切正常,我需要在创建实例时从 Learner class 传递给 Mappers 构造函数什么?

如果使用依赖注入,那么应该重构 classes 以允许使用服务抽象和通过构造函数注入显式依赖原则。

学习者 class 和抽象

public interface ILearner {
    string GetLearner();
}

public class Learner : ILearner {
    private readonly IMappers mappers;

    public Learner(IMappers mappers) {
        this.mappers = mappers;
    }

    public string GetLearner() {    
        LearnerDTO learnerDTO = JsonFactory.LoadJson();
        LearnerModel learnerModel = mappers.LearnerDTOtoLearnerModel(learnerDTO);            
    }    
}

映射器 class和抽象

public interface IMappers {
    LearnerModel LearnerDTOtoLearnerModel(LearnerDTO learnerDto);
}

public class Mappers : IMappers {
    private readonly IMapper _mapper;

    public Mappers(IMapper mapper) {
        _mapper = mapper;
    }

    public LearnerModel LearnerDTOtoLearnerModel(LearnerDTO learnerDto) {
        LearnerModel model = _mapper.Map<LearnerModel>(learnerDto);    
        return model;
    }
}

所有内容都应该注册到依赖容器中,这将用于解析服务并执行所需的功能。

控制台

class Program {
    static void Main() {
        var services = new ServiceCollection();
        services.AddAutoMapper(typeof(AutoMapping));
        
        //use the lifetime that suits your needs
        //but for this example I am using transient
        services.AddTransient<ILearner, Learner>(); 
        services.AddTransient<IMappers, Mappers>();
        
        IServiceProvider serviceProvider = services.BuildServiceProvider();

        ILearner learner = serviceProvider.GetRequiredService<ILearner>();

        //...            
    }
}