Ale*_*hke 3 asp.net-mvc castle-windsor automapper
我有一个ASP.NET MVC应用程序,其中所有映射都以这种方式在引导期间注册:
Mapper.CreateMap<AdvicesModel, Advices>();
到目前为止,我们静态地使用了它"旧"的方式:
Mapper.Map<Advice>(adviceDto)
到现在为止还挺好.
更新到AutoMapper的第4版后,我发现建议使用它来构建实例.有人能指出我如何正确地指示Castle将AutoMapper的实例注入我的依赖项并且不是静态地使用它.
我想象的是这样的:
var viewModel = mapper.Map<CartViewModel>(cart);
与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)));
    }
我不确定这是否理想/最佳等,但似乎确实有效:-)
对于原生的ASP.net 5 DI:
Run Code Online (Sandbox Code Playgroud)public class YourProfile : Profile { protected override void Configure(){ //CreateMap<T, TDto>().ForMember.... } }
Run Code Online (Sandbox Code Playgroud)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)public class Repository{ private readonly IMapper _mapper; public Repository(IMapper mapper){ _mapper = mapper; } public List<TDto> ToDtoList<TDto>(){ return _mapper.Map<List<TDto>>(sourceList); } }
| 归档时间: | 
 | 
| 查看次数: | 5351 次 | 
| 最近记录: |