1. 程式人生 > 其它 >在Prism中使用AutoMapper進行模型對映

在Prism中使用AutoMapper進行模型對映

在Prism中可以使用反射進行模型對映,但是這種對映方式對Model和DTO中相同欄位不同型別就無能為力了,或者需要複雜的處理才能達成目標。

使用AutoMapper進行模型對映就簡單多了,但是其在Prism中的應用很少,在.Net環境下一般應用於Asp .Net Core居多。經過一番搜尋和摸索,在“使用帶有DI容器的AutoMapper例項化型別”這篇文章中受到啟發,終於實現Prism環境中AutoMapper的使用了。

本文開發環境:VS2019 16.9.5,WPF(.NET 5.0),AutoMapper 10.1.1。

一、模型預設

public class Student
{
    
public int Id { get; set; } public string Name { get; set; } public bool? Gender { get; set; } public DateTime Birthday { get; set; } } public class StudentDto { public int Id { get; set; } public string Name { get; set; } public string Birthday { get; set; } }

二、使用反射

還是介紹下使用反射進行模型對映的方法,主要是遍歷被轉換的模型的屬性,獲取轉換後模型的屬性,並對其進行賦值。

public static StudentDto GetStudentDtoByReflection(Student student)
{
    var studentDto = new StudentDto();
    var studentDtoType = typeof(StudentDto);
    var studentType = typeof(Student);

    var properties = studentType.GetProperties();
    foreach (var property in properties)
    {
        
var propertyInfo = studentDtoType.GetProperty(property.Name); propertyInfo?.SetValue(studentDto, property.GetValue(student)); } return studentDto; }

三、使用AutoMapper

在AutoMapper中需要使用MapperConfiguration進行配置,然後通過該類的物件獲取IMapper物件,最後才能進行模型對映。

1、建立Profile

public class StudentProfile : Profile
{
    public StudentProfile()
    {
        CreateMap<Student, StudentDto>()
            .ForMember(
                dest => dest.Birthday,
                opt => opt.MapFrom(src => $@"{src.Birthday:yyyy-MM-dd HH:mm:ss}")
            );
    }
}

2、封裝MapperConfiguration

封裝MapperConfiguration,對外提供IMapper物件。

public interface IAutoMapperProvider
{
    IMapper GetMapper();
}

public class AutoMapperProvider : IAutoMapperProvider
{
    private readonly MapperConfiguration _configuration;

    public AutoMapperProvider(IContainerProvider container)
    {
        _configuration = new MapperConfiguration(configure =>
        {
            configure.ConstructServicesUsing(container.Resolve);

            //掃描profile檔案
            configure.AddMaps(AppDomain.CurrentDomain.GetAssemblies());
        });
    }

    public IMapper GetMapper()
    {
        return _configuration.CreateMapper();
    }
}

3、注入IOC容器

將IAutoMapperProvider注入IOC容器,並對外提供IMapper注入型別。

protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
    //註冊AutoMapper
    containerRegistry.RegisterSingleton<IAutoMapperProvider, AutoMapperProvider>();
    containerRegistry.Register(typeof(IMapper), GetMapper);
}

private IMapper GetMapper(IContainerProvider container)
{
    var provider = container.Resolve<IAutoMapperProvider>();
    return provider.GetMapper();
}

4、使用AutoMapper

通過依賴注入,使用IMapper進行模型對映。

public class TestViewModel : BindableBase
{
    private readonly IMapper _mapper;

    public TestViewModel(IMapper mapper)
    {
        _container = container;
    }
}

方法1,對映單個物件。

private StudentDto GetStudentDtoByAutoMapper(Student student)
{
    return _mapper.Map<StudentDto>(student);
}

方法2,對映集合。

var studentDtoList = _mapper.Map<IList<Student>, IList<StudentDto>>(studentList);