var expression = app.UseAutoMapper();
expression.CreateMap<Foo, FoodDto>();
这样就完成了DI版本的AutoMapper
调用例子代码如下
public class ValuesController : ControllerBase
{
private IMapper Mapper { get; }
public ValuesController(IMapper mapper)
{
Mapper = mapper;
}
// GET api/values
[HttpGet]
public FoodDto Get()
{
var model = new Foo()
{
Id = Guid.NewGuid(),
Name = "test",
Money = 15.0m
};
return Mapper.Map<FoodDto>(model);
}
}
public static class AutoMapperHelper
{
private static IServiceProvider ServiceProvider;
public static void UseStateAutoMapper(this IApplicationBuilder applicationBuilder)
{
ServiceProvider = applicationBuilder.ApplicationServices;
}
public static TDestination Map<TDestination>(object source)
{
var mapper = ServiceProvider.GetRequiredService<IMapper>();
return mapper.Map<TDestination>(source);
}
public static TDestination Map<TSource, TDestination>(TSource source)
{
var mapper = ServiceProvider.GetRequiredService<IMapper>();
return mapper.Map<TSource, TDestination>(source);
}
}
app.UseStateAutoMapper();
[HttpGet("Static")]
public FoodDto Static()
{
var model = new Foo()
{
Id = Guid.NewGuid(),
Name = "test",
Money = 15.0m
};
return AutoMapperHelper.Map<FoodDto>(model);
}
public static class AutoMapperHelper
{
...
public static TDestination MapTo<TSource, TDestination>(this TSource source)
{
var mapper = ServiceProvider.GetRequiredService<IMapper>();
return mapper.Map<TSource, TDestination>(source);
}
public static TDestination MapTo<TDestination>(this object source)
{
var mapper = ServiceProvider.GetRequiredService<IMapper>();
return mapper.Map<TDestination>(source);
}
}
[HttpGet("Static")]
public FoodDto Static()
{
var model = new Foo()
{
Id = Guid.NewGuid(),
Name = "test",
Money = 15.0m
};
return model.MapTo<FoodDto>();
}
//[HttpGet("Static")]
//public FoodDto Static()
//{
// var model = new Foo()
// {
// Id = Guid.NewGuid(),
// Name = "test",
// Money = 15.0m
// };
// return model.MapTo<Foo, FoodDto>();
//}