简体   繁体   English

如何在没有 DI 的情况下将 AutoMapper 9 与 static 实现一起使用?

[英]How to use AutoMapper 9 with static implementation without DI?

I want to create static implementation of AutoMapper without dependency injection.我想在没有依赖注入的情况下创建 AutoMapper 的 static 实现。 I'm using ASP.NET CORE 2.2 and AutoMapper 9. I've found similar topic:我正在使用 ASP.NET CORE 2.2 和 AutoMapper 9。我发现了类似的主题:

How to use AutoMapper 9.0.0 in Asp.Net Web Api 2 without dependency injection? 如何在没有依赖注入的情况下在 Asp.Net Web Api 2 中使用 AutoMapper 9.0.0?

Is there any simpler way to create static implementation without DI?有没有更简单的方法来创建没有 DI 的 static 实现?

You can simply build a mapper from the mapper configuration.您可以简单地从映射器配置构建映射器。 An example is provided in the AutoMapper docs , which I have reproduced here: AutoMapper docs中提供了一个示例,我在此处复制了该示例:

// use cfg to configure AutoMapper
var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDto>()); 

var mapper = config.CreateMapper();
// or
var mapper = new Mapper(config);
OrderDto dto = mapper.Map<OrderDto>(order);

Then you could simply set a static field/property somewhere in your project to hold mapper .然后,您可以简单地在项目中的某处设置一个static字段/属性来保存mapper

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM