https://www.jianshu.com/p/f66447282780

 

依赖注入(Dependency Injection)

AutoMapper支持使用静态服务定位构建自定义值解析器和自定义类型转换器的功能:

Mapper.Initialize(cfg =>
{
cfg.ConstructServicesUsing(ObjectFactory.GetInstance); cfg.CreateMap<Source, Destination>();
});

或者在基于实例的容器(包括子/嵌套容器)中使用动态服务定位:

var mapper = new Mapper(Mapper.Configuration, childContainer.GetInstance);

var dest = mapper.Map<Source, Destination>(new Source { Value = 15 });

陷阱

使用IQueryable.ProjectTo扩展方法与使用依赖注入是互斥的。请使用
IEnumerable.Select(_mapper.Map<DestinationType>).ToList() 来代替IQueryable.ProjectTo

ASP.NET Core

有一个NuGet包与这里描述的默认注入机制搭配使用。

Ninject

对于那些使用Ninject的人来说,这有一个AutoMapper使用的Ninject模块的例子

public class AutoMapperModule : NinjectModule
{
public override void Load()
{
Bind<IValueResolver<SourceEntity, DestModel, bool>>().To<MyResolver>(); var mapperConfiguration = CreateConfiguration();
Bind<MapperConfiguration>().ToConstant(mapperConfiguration).InSingletonScope(); // This teaches Ninject how to create automapper instances say if for instance
// MyResolver has a constructor with a parameter that needs to be injected
Bind<IMapper>().ToMethod(ctx =>
new Mapper(mapperConfiguration, type => ctx.Kernel.Get(type)));
} private MapperConfiguration CreateConfiguration()
{
var config = new MapperConfiguration(cfg =>
{
// Add all profiles in current assembly
cfg.AddProfiles(GetType().Assembly);
}); return config;
}
}

简单注入器实现

工作流程如下:

  1. 通过 MyRegistrar.Register注册你的类型
  2. MapperProvider允许你直接将IMapper的实例注入到其他类中
  3. SomeProfile使用PropertyThatDependsOnIocValueResolver解析值
  4. PropertyThatDependsOnIocValueResolverIService注入其中

ValueResolver能访问IService,是因为我们通过MapperConfigurationExpression.ConstructServicesUsing注册容器。

public class MyRegistrar
{
public void Register(Container container)
{
// Injectable service
container.RegisterSingleton<IService, SomeService>(); // Automapper
container.RegisterSingleton(() => GetMapper(container));
} private AutoMapper.IMapper GetMapper(Container container)
{
var mp = container.GetInstance<MapperProvider>();
return mp.GetMapper();
}
} public class MapperProvider
{
private readonly Container _container; public MapperProvider(Container container)
{
_container = container;
} public IMapper GetMapper()
{
var mce = new MapperConfigurationExpression();
mce.ConstructServicesUsing(_container.GetInstance); var profiles = typeof(SomeProfile).Assembly.GetTypes()
.Where(t => typeof(Profile).IsAssignableFrom(t))
.ToList(); mce.AddProfiles(profiles); var mc = new MapperConfiguration(mce);
mc.AssertConfigurationIsValid(); IMapper m = new Mapper(mc, t => _container.GetInstance(t)); return m;
}
} public class SomeProfile : Profile
{
public SomeProfile()
{
var map = CreateMap<MySourceType, MyDestinationType>();
map.ForMember(d => d.PropertyThatDependsOnIoc, opt => opt.ResolveUsing<PropertyThatDependsOnIocValueResolver>());
}
} public class PropertyThatDependsOnIocValueResolver : IValueResolver<MySourceType, object, int>
{
private readonly IService _service; public PropertyThatDependsOnIocValueResolver(IService service)
{
_service = service;
} int IValueResolver<MySourceType, object, int>.Resolve(MySourceType source, object destination, int destMember, ResolutionContext context)
{
return _service.MyMethod(source);
}
}

码字不易,动动手指给个赞吧

14.AutoMapper 之依赖注入(Dependency Injection)的更多相关文章

  1. 控制反转Inversion of Control (IoC) 与 依赖注入Dependency Injection (DI)

    控制反转和依赖注入 控制反转和依赖注入是两个密不可分的方法用来分离你应用程序中的依赖性.控制反转Inversion of Control (IoC) 意味着一个对象不会新创建一个对象并依赖着它来完成工 ...

  2. 简明依赖注入(Dependency Injection)

    前言 这是因特奈特上面不知道第几万篇讲依赖注入(Dependency Injection)的文章,但是说明白的却寥寥无几,这篇文章尝试控制字数同时不做大多数. 首先,依赖注入的是一件很简单的事情. 为 ...

  3. Spring点滴七:Spring中依赖注入(Dependency Injection:DI)

    Spring机制中主要有两种依赖注入:Constructor-based Dependency Injection(基于构造方法依赖注入) 和 Setter-based Dependency Inje ...

  4. 依赖注入 | Dependency Injection

    原文链接: Angular Dependency Injection翻译人员: 铁锚翻译时间: 2014年02月10日说明: 译者认为,本文中所有名词性的"依赖" 都可以理解为 & ...

  5. 设计模式之————依赖注入(Dependency Injection)与控制反转(Inversion of Controller)

    参考链接: 依赖注入(DI) or 控制反转(IoC) laravel 学习笔记 —— 神奇的服务容器 PHP 依赖注入,从此不再考虑加载顺序 名词解释 IoC(Inversion of Contro ...

  6. 理解依赖注入(Dependency Injection)

    理解依赖注入 Yii2.0 使用了依赖注入的思想.正是使用这种模式,使得Yii2异常灵活和强大.千万不要以为这是很玄乎的东西,看完下面的两个例子就懂了. class SessionStorage { ...

  7. AngularJS - 依赖注入(Dependency Injection)

    点击查看AngularJS系列目录 转载请注明出处:http://www.cnblogs.com/leosx/ 依赖注入 依赖注入是软件设计模式中的一部分,用于处理组件是如何得到它说依赖的其它组件的. ...

  8. Spring之对象依赖关系(依赖注入Dependency Injection)

    承接上篇: Spring中,如何给对象的属性赋值: 1:通过构造函数,如下所示: <!-- 1:构造函数赋初始值 --><bean id="user1" clas ...

  9. MVC使用StructureMap实现依赖注入Dependency Injection

    使用StructureMap也可以实现在MVC中的依赖注入,为此,我们不仅要使用StructureMap注册各种接口及其实现,还需要自定义控制器工厂,借助StructureMap来生成controll ...

随机推荐

  1. [BZOJ2002][洛谷P3203][Hnoi2010]Bounce 弹飞绵羊(LCT维护链长)

    luogu传送门 2002: [Hnoi2010]Bounce 弹飞绵羊 Time Limit: 10 Sec  Memory Limit: 259 MBSubmit: 16082  Solved:  ...

  2. EPPlus生成Excel表格(只支持2007及以上)

    主要来源: https://www.cnblogs.com/rumeng/p/3785748.html http://epplus.codeplex.com/ FileInfo newFile = n ...

  3. LinkedList,ArrayList,Vector,HashMap,HashSet,HashTable之间的区别与联系

    在编写java程序中,我们最常用的除了八种基本数据类型,String对象外还有一个集合类,在我们的的程序中到处充斥着集合类的身影!java中集合大家族的成员实在是太丰富了,有常用的ArrayList. ...

  4. BOSCH汽车工程手册————驾驶员辅助系统

    根据交通事故统计得出平均每分钟有一人死于交通事故 而辅助驾驶系统能够为驾驶员洞察了解汽车周围情况,识别危险的行驶状况. 提早为驾驶员告诉危险信息,可减少60%汽车驶上主路事故和1/3汽车前碰事故. 有 ...

  5. OPCDAAuto的一个坑

    最近项目需要对SCADA系统的下位机采集实时数据,常见做法是两种,一种采用ModBus RTU/TCP协议直接通过支持ModBus的下位机通信,一种是通过OPC规范,使用厂商提供的OPC Server ...

  6. 基于java config的springSecurity--session并发控制

    原作地址:http://blog.csdn.net/xiejx618/article/details/42892951 参考资料:spring-security-reference.pdf的Sessi ...

  7. jquery.validate.js使用之自定义表单验证规则

    jquery.validate.js使用之自定义表单验证规则,下面列出了一些常用的验证法规则 jquery.validate.js演示查看 jquery validate强大的jquery表单验证插件 ...

  8. git pull 覆盖本地代码

    在使用Git的过程中,有些时候我们只想要git服务器中的最新版本的项目,对于本地的项目中修改不做任何理会,就需要用到Git pull的强制覆盖,具体代码如下: $ git fetch --all $ ...

  9. 【DVWA】SQL Injection(SQL 注入)通关教程

    日期:2019-07-28 20:43:48 更新: 作者:Bay0net 介绍: 0x00.基本信息 关于 mysql 相关的注入,传送门. SQL 注入漏洞之 mysql - Bay0net - ...

  10. overflow-x scroll 内部元素滚动,父级容器代码

    display: -webkit-box; overflow-x: scroll; -webkit-overflow-scrolling: touch;