注入AutoMapper实例

Ale*_*hke 3 asp.net-mvc castle-windsor automapper

我有一个ASP.NET MVC应用程序,其中所有映射都以这种方式在引导期间注册:

Mapper.CreateMap<AdvicesModel, Advices>();
Run Code Online (Sandbox Code Playgroud)

到目前为止,我们静态地使用了它"旧"的方式:

Mapper.Map<Advice>(adviceDto)
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好.

更新到AutoMapper的第4版后,我发现建议使用它来构建实例.有人能指出我如何正确地指示Castle将AutoMapper的实例注入我的依赖项并且不是静态地使用它.

我想象的是这样的:

var viewModel = mapper.Map<CartViewModel>(cart);
Run Code Online (Sandbox Code Playgroud)

IMapper实例注入.

小智 6

我不认为services.AddSingleton <>是Castle Windsor,所以下面是我的CastleWindsor安装程序.

        private static void RegisterProfilesAndResolvers(IWindsorContainer container)
    {
        // register value resolvers
        container.Register(Types.FromAssembly(Assembly.GetExecutingAssembly()).BasedOn<IValueResolver>());

        // register profiles
        container.Register(Types.FromThisAssembly().BasedOn<Profile>().WithServiceBase().Configure(c => c.Named(c.Implementation.FullName)).LifestyleTransient());

        var profiles = container.ResolveAll<Profile>();

        var config = new MapperConfiguration(cfg =>
        {
            foreach (var profile in profiles)
            {
                cfg.AddProfile(profile);
            }
        });

        container.Register(Component.For<MapperConfiguration>()
            .UsingFactoryMethod(() => config));

        container.Register(
            Component.For<IMapper>().UsingFactoryMethod(ctx => ctx.Resolve<MapperConfiguration>().CreateMapper(ctx.Resolve)));
    }
Run Code Online (Sandbox Code Playgroud)

我不确定这是否理想/最佳等,但似乎确实有效:-)


Rex*_*Rex 5

对于原生的ASP.net 5 DI:

  1. 创建一个扩展AutoMapper.Profile的新类,使用单个覆盖的Configure,在Configure中创建所有映射.
public class YourProfile : Profile
{
   protected override void Configure(){
       //CreateMap<T, TDto>().ForMember....   
   }
}
Run Code Online (Sandbox Code Playgroud)
  1. 在startup.cs中,设置DI如下:
 public void ConfigureServices(IServiceCollection services)
 {
  //...
   var config = new MapperConfiguration(cfg =>
   {
     cfg.AddProfile(new YourProfile());
   });
   services.AddSingleton<IMapper>(sp => config.CreateMapper())
  //...
 }
Run Code Online (Sandbox Code Playgroud)
  1. 现在注射:
public class Repository{
    private readonly IMapper _mapper;
    public Repository(IMapper mapper){
        _mapper = mapper;
    }
    public List<TDto> ToDtoList<TDto>(){
     return _mapper.Map<List<TDto>>(sourceList);
    }
 }
Run Code Online (Sandbox Code Playgroud)

来源: https://pintoservice.wordpress.com/2016/01/31/dependency-injection-for-automapper-4-2-in-asp-net-vnext-mvc-project/