AddAutoMapper 不会加载 asp.net 核心中的所有程序集 [英] AddAutoMapper does not load all assemblies in asp.net core
问题描述
我有以下代码将自动映射器添加到我的应用程序中.
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?
推荐答案
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 methodAddAutoMapper
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 核心中的所有程序集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!