我有以下代码将自动映射器添加到我的应用中.
I have the following code that add automapper to my app.
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddHttpClient(); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); }AppDomain.CurrentDomain.GetAssemblies()仅返回在调用时加载的程序集.我可以看到某些包含我的映射的程序集尚未加载,结果未加载映射,这会向我返回有关缺少映射类型的错误.
The AppDomain.CurrentDomain.GetAssemblies() returns only assemblies that were loaded at the time it is called. I can see that some of my assemblies which contain my mappings have not been yet loaded and as a result mappings are not loaded which returns me errors about missing map types.
如何获取我的项目引用的所有程序集?
How do I get all assemblies referenced by my project?
推荐答案参考-来自AutoMapper官方文档
ASP.NET Core
有一个 NuGet包与此处中所述的默认注入机制,并在此项目.
There is a NuGet package to be used with the default injection mechanism described here and used in this project.
您使用配置文件定义配置.然后你让AutoMapper知道这些配置文件在哪些程序集中定义在以下位置调用 IServiceCollection 扩展方法 AddAutoMapper 启动:
You define the configuration using profiles. And then you let AutoMapper know in what assemblies are those profiles defined by calling the IServiceCollection extension method AddAutoMapper at startup:
services.AddAutoMapper(profileAssembly1, profileAssembly2 /*, ...*/);或标记类型:
services.AddAutoMapper(typeof(ProfileTypeFromAssembly1), typeof(ProfileTypeFromAssembly2) /*, ...*/);现在,您可以在运行时将AutoMapper注入服务/控制器:
Now you can inject AutoMapper at runtime into your services/controllers:
public class EmployeesController { private readonly IMapper _mapper; public EmployeesController(IMapper mapper) => _mapper = mapper; // use _mapper.Map or _mapper.ProjectTo }更多推荐
AddAutoMapper不会在asp.net核心中加载所有程序集
发布评论