我可以将 AutoMapper 与 Blazor 一起使用吗?

Can I use AutoMapper with Blazor?

我可以将 AutoMapper 8.0.1 与 Blazor 服务器应用程序一起使用吗? 我试过了,但我的代码总是 运行 出错:

Missing type map configuration or unsupported mapping. Mapping types: Object -> Object System.Object -> System.Object

我已将映射器添加到启动文件中:

services.AddAutoMapper(typeof(Startup));

我已经创建了个人资料:

public class MyProfile : Profile
{
    public MyProfile()
    {
        CreateMap<District, DistrictModel>();
    }
}

我尝试使用它:

[Inject]
protected IMapper Mapper { get; set; }
District district = DistrictService.FindDistrictById(districtId);
DistrictModel model = Mapper.Map<DistrictModel>(district);

AssertConfigurationIsValid 方法给出:

Cannot find any profiles with the name 'MyProfile'. (Parameter 'profileName')

Startup.cs

var mapperConfiguration = new MapperConfiguration(configuration =>
{
    configuration.AddProfile(new MyProfile());
});

var mapper = mapperConfiguration.CreateMapper();

services.AddSingleton(mapper);

在启动时将其添加到您的服务中:

它可重复使用且更清洁

 public void ConfigureServices(IServiceCollection services)
{
            services.AddAutoMapper(Assembly.GetExecutingAssembly());
}

将这些添加到界面并 class 在您的项目中

public interface IMapFrom<T>
{
        void Mapping(Profile profile) => profile.CreateMap(typeof(T), GetType());
}
using AutoMapper;
using System;
using System.Linq;
using System.Reflection;

    public class MappingProfile : Profile
    {
        public MappingProfile()
        {
            ApplyMappingsFromAssembly(Assembly.GetExecutingAssembly());
        }

        private void ApplyMappingsFromAssembly(Assembly assembly)
        {
                var types = assembly.GetExportedTypes()
                .Where(t => t.GetInterfaces()
                .Any(i =>i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapFrom<>)))
                .ToList();

            foreach (var type in types)
            {
                var instance = Activator.CreateInstance(type);

                var methodInfo = type.GetMethod("Mapping")
                    ?? type.GetInterface("IMapFrom`1").GetMethod("Mapping");

                methodInfo?.Invoke(instance, new object[] { this });

            }
        }
    }

您的模型或视图模型:

 public class District : IMapFrom<District>
    {
        public string PhoneNumber { get; set; }
        public string Password { get; set; }

        public void Mapping(Profile profile)
        {
            profile.CreateMap<District, DistrictModel>();
        }
    }