我想将 Automapper 配置文件放在我的业务层中

I want to place Automapper profile in my Business Layer

我创建了一个 Web api 核心 2.0 应用程序。 我有我的主要应用程序和业务层。 我想将自动映射器配置文件放在业务层中,以便所有映射都在业务层中进行。我的业务层只是一个class库项目。

这可能吗?还是我需要将所有映射放在主应用程序的配置文件 class 中?

理论上的解释会有所帮助。

是的,这是可能的,但这取决于模型 classes 所在的位置。

您可以为每个层或项目提供一个 Profile,您可以在其中映射适当的模型 classes。然后在要使用映射器的项目中,创建 ObjectMapper class 以加载配置文件。

namespace BL.Config
{
    public class MapperProfile : Profile
    {
        public MapperProfile()
        {
            CreateMap<Entity, Dto>();
            ...
        }
    }

    public class ObjectMapper
    {
        public static IMapper Mapper
        {
            get { return mapper.Value; }
        }

        public static IConfigurationProvider Configuration
        {
            get { return config.Value; }
        }

        public static Lazy<IMapper> mapper = new Lazy<IMapper>(() =>
        {
            var mapper = new Mapper(Configuration);
            return mapper;
        });

        public static Lazy<IConfigurationProvider> config = new Lazy<IConfigurationProvider>(() =>
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile<BL.Config.MapperProfile>();
                cfg.AddProfile<AppCore.Config.MapperProfile>();  // any other profiles you need to use
            });

            return config;
        });
    }
}

当我需要使用 AutoMapper 时,我使用 ObjectMapper.Mapper 来获取我的映射器实例。我喜欢将其添加到抽象服务中。

public interface IAutoMapperService
{
    IMapper Mapper { get; }
}

public abstract class AutoMapperService : IAutoMapperService
{
    public IMapper Mapper
    {
        get { return BAL.Config.ObjectMapper.Mapper; }
    }
}

以及用法:服务有Mapper成员。

public class SomeService : AutoMapperService, ISomeService
{
    public Foo GetFoo()
    {
        var foo = Mapper.Map<Foo>(bar);
        return foo;
    }
}

或者,如果您不能继承另一个基础 class,则只实施 IAutoMapperService

缺点是 BL 需要 AutoMapper 依赖项。但是使用这种方式我发现我可以从其他层隐藏很多模型。