我使用的是asp.net core 2.0。我的解决方案中有 DataAccess 项目和 20 个 API 服务项目。而且这个数字每天都在增加。我将使用 AutoMapper。但我不想为所有项目添加 NuGet 的自动映射器。因此,我想添加到唯一的 DataAccess 解决方案并将配置文件添加到 DataAccess 解决方案。我想通过编写“mapper.Map(originalObject)”从 API 项目进行调用。我们可以通过添加startup.cs将Automapper添加到API项目中。但我的DataAccess项目是一个类库。所以它没有startup.cs。我该如何做到这一点以及我可以从服务项目访问自动映射器吗? (我不想将自动映射器从 NuGet 添加到 API)
这个问题可能有很多解决方案,我只建议其中两种,这些方法也可能根据您的选择和场景而改变。您的辅助类是否知道将要映射的所有类型,或者其他用户库是否需要注册自己的 POCO 类,您是否更喜欢创建映射器...您可能还希望缓存映射器并在再次请求时返回它。
简单代码示例如下
class Foo
{
public string Name { get; set; }
}
class Bar
{
public string Name { get; set; }
}
static void Main(string[] args)
{
//First approach usage
Bar _bar1 = MapperHelper.MapFrom<Bar>(new Foo() { Name = "bbbbb" });
//Second approach usage
IMyMapper _myMapper = MapperHelper.GetMapperFor<Foo, Bar>();
Bar _bar2 = _myMapper.MapFrom<Bar>(new Foo() { Name = "aaaAAA" });
//Third approach usage
Bar _bar3 = MapperHelper.Map<Bar, Foo>(new Foo() { Name = "cccc" });
}
public interface IMyMapper
{
T MapFrom<T>(object entity);
}
class MyMapper : IMyMapper
{
IMapper mapper;
public MyMapper(IMapper mapper)
{
this.mapper = mapper;
}
public T MapFrom<T>(object entity)
{
return mapper.Map<T>(entity);
}
}
public static class MapperHelper
{
static IMapper staticMapper;
static MapperHelper()
{
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<Foo, Bar>();
});
staticMapper = config.CreateMapper();
}
//First approach, create a mapper and use it from a static method
public static T MapFrom<T>(object entity)
{
return staticMapper.Map<T>(entity);
}
//Second approach (if users need to use their own types which are not known by this project)
//Create you own mapper interface ans return it
public static IMyMapper GetMapperFor<TSource, TDestination>()
{
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<TSource, TDestination>();
});
var _mapper = config.CreateMapper();
return new MyMapper(_mapper);
}
//Third sample, create and use mapper inside a static helper method
//This is for mapping foreign types that this project does not
//include (e.g POCO or model types in other projects)
public static TDestination Map<TDestination, TSource>(TSource entity)
{
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<TSource, TDestination>();
});
var _mapper = config.CreateMapper();
return _mapper.Map<TDestination>(entity);
}
}
第一个为已知类型创建配置并使用此映射器。 第二个创建一个映射器并在包装器类中返回它。 第三个创建并使用映射器进行映射操作,并且仅返回映射的对象。
大多数人不喜欢静态类和方法,因为它们会导致严格的不需要的依赖关系,并且不能轻易替换。因此,首选创建工厂或实用程序类,将它们注册到依赖注入容器并将它们注入到需要的地方。
共享项目:
namespace App.Shared.Common;
public class AutoMapper : Profile
{
public AutoMapper()
{
CreateMap<Client, ClientDto>().ReverseMap();
}
}
主要项目:
namespace App.API.Common;
public class MyAutoMapper : App.Shared.Common.AutoMapper
{
public MyAutoMapper() : base() { }
}
程序.cs
builder.Services.AddAutoMapper(typeof(Program));
这项工作是我做的。