0
我試圖與微軟內置的依賴注入到註冊新Automapper 5.0:如何使用Microsoft依賴注入註冊Automapper 5.0?
public static class ServicesContainerConfigure
{
public static void Configure(IServiceCollection services)
{
//This line fails because Mapper has no default constructor
services.TryAddScoped<IMapper, Mapper>();
var profileType = typeof(Profile);
// Get an instance of each Profile in the executing assembly.
var profiles = Assembly.GetExecutingAssembly().GetTypes()
.Where(t => profileType.IsAssignableFrom(t)
&& t.GetConstructor(Type.EmptyTypes) != null)
.Select(Activator.CreateInstance)
.Cast<Profile>();
// Initialize AutoMapper with each instance of the profiles found.
var config = new MapperConfiguration(cfg =>
{
foreach (var profile in profiles)
{
cfg.AddProfile(profile);
}
});
config.CreateMapper();
}
}
有一個在映射對象沒有默認構造函數。必須有一種方法來註冊它,而無需在映射器dll中註冊所有注入的對象。