I want to place Automapper profile in my Business Layer

孤街浪徒 提交于 2019-12-11 11:04:22

问题


I've created a web api core 2.0 application. I've got my main app and the Business Layer. I want to place the automapper profile in the business layer so that all the mappings are made in the business layer. My business layer is just a class library project.

Is this possible? or do I need to place all my mapping in a Profile class in the main app?

Just a theoretical explanation can help.


回答1:


Yes, it's possible but it depends on where the model classes reside.

You can give each layer or project a Profile where you map the appropriate model classes. Then in the project where you want to use the mapper, create the ObjectMapper class to load the 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;
        });
    }
}

When I need to use AutoMapper, I use the ObjectMapper.Mapper to get my mapper instance. I like to add this to an abstract service.

public interface IAutoMapperService
{
    IMapper Mapper { get; }
}

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

And usage: The service has the Mapper member.

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

Or just implement the IAutoMapperService if you can't inherit another base class.

The downside is BL requires the AutoMapper dependency. But using this way I find I can hide many models from the other layers.



来源:https://stackoverflow.com/questions/49312728/i-want-to-place-automapper-profile-in-my-business-layer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!