【问题标题】:I want to place Automapper profile in my Business Layer我想在我的业务层中放置 Automapper 配置文件
【发布时间】:2018-10-13 02:00:19
【问题描述】:

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

这可能吗?还是我需要将所有映射放在主应用程序的 Profile 类中?

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

【问题讨论】:

    标签: asp.net-core .net-core automapper asp.net-core-2.0 asp.net-core-webapi


    【解决方案1】:

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

    您可以给每个层或项目一个Profile,您可以在其中映射适当的模型类。然后在要使用映射器的项目中,创建ObjectMapper类来加载Profiles。

    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;
        }
    }
    

    如果你不能继承另一个基类,或者只是实现IAutoMapperService

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

    【讨论】:

    • 拯救了我的一天,谢谢。只有一件事,我认为您的 ObjectMapper.config 缺少return config;。至少我必须添加它才能让它工作。
    • @HSBallina 是的,它不见了。
    • @Jasen 如何在控制器中实现 IAutoMapperService?
    • @Ljt 声明一个IMapper Mapper getter 属性,该属性从您的ObjectMapper 类返回您配置的映射器。你几乎可以从我上面的 AutoMapperService 中复制它。
    猜你喜欢
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 2021-09-27
    • 1970-01-01
    • 2012-02-23
    相关资源
    最近更新 更多