2016-07-05 34 views
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中註冊所有注入的對象。

回答

1

AddXXX方法通常會提供一個超載,您可以通過一個「實現工廠」。這似乎TryAddXXX不通過。如果沒有令人信服的理由使用TryAddXXX那麼這應該適合你:

services.AddScoped<IMapper>(_ => 
{ 
    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); 
     } 
    }); 

    return config.CreateMapper(); 
});