我试图找出我的应用程序的Startup.cs文件来配置AutoMapper,然后用它在我的应用程序的正确方法。配置AutoMapper 4.2,内置在国际奥委会ASP.NET 1.0的核心MVC6
我想使用this documentation这在一定程度解释了如何仍给AutoMapper静态的感觉没有老静态API。该示例使用StructureMap。
我想知道我可以做同样的事情,但在使用内置的服务容器中的核心应用程序1.0。
我假设在配置功能我将配置AutoMapper然后在ConfigureServices功能我将其添加为一过性。
我假设最后最干净和最正确的方法是使用依赖注入。这是我当前的尝试,但它不工作:
Startup.cs
public IMapper Mapper { get; set; }
private MapperConfiguration MapperConfiguration { get; set; }
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IMapper, Mapper>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
MapperConfiguration MapperConfiguration = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Product, ProductViewModel>().ReverseMap();
});
Mapper = MapperConfiguration.CreateMapper();
}
在我的控制器:
private IMapper _mapper { get; set; }
// Constructor
public ProductsController(IMapper mapper)
{
_mapper = mapper;
}
public IActionResult Create(ProductViewModel vm)
{
Product product = _mapper.Map<ProductViewModel, Product>(vm);
}
它根本无法所有工作..我必须错过一些步骤或做错事。
我没有这样做的完整的答案(它挣扎喽!),但在你的AddTransient,第二通用参数是Mapper的*类型*而不是使用CreateMapper创建的Mapper实例。我猜这将是沿着services.AddInstance的行。 – DavidGouge