问题
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());
}
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?
回答1:
Reference - From official AutoMapper docs
ASP.NET Core
There is a NuGet package to be used with the default injection mechanism described here and used in this project.
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 /*, ...*/);
or marker types:
services.AddAutoMapper(typeof(ProfileTypeFromAssembly1), typeof(ProfileTypeFromAssembly2) /*, ...*/);
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
}
来源:https://stackoverflow.com/questions/58129450/addautomapper-does-not-load-all-assemblies-in-asp-net-core