如何使用StructureMap注入AutoMapper IMappingEngine [英] How to inject AutoMapper IMappingEngine with StructureMap
问题描述
我为 Automapper 找到的大多数示例都使用静态Mapper对象来管理类型映射。对于我的项目,我需要使用StructureMap注入一个IMapperEngine作为对象构造的一部分,以便我们可以在单元测试中模拟映射器,所以我们不能使用静态映射器。我还需要支持配置AutoMapper配置文件。
Most of the examples I've found for Automapper use the static Mapper object for managing type mappings. For my project, I need to inject an IMapperEngine as part of object construction using StructureMap so that we can mock the mapper in unit tests so we can't use the static mapper. I also need to support configuring AutoMapper Profiles.
我的问题是如何配置StructureMap注册表,以便在构建MyService实例时可以提供一个IMappingEngine的实例。
My question is how can I configure the StructureMap registry so that it can supply an instance of IMappingEngine when an instance of MyService is constructed.
这里是服务构造函数签名:
Here is the Service constructor signature:
public MyService(IMappingEngine mapper, IMyRepository myRepository, ILogger logger)
这里是StructureMap注册表
And here is the StructureMap Registry
public class MyRegistry : StructureMap.Configuration.DSL.Registry
{
public MyRegistry()
{
For<IMyRepository>().Use<MyRepository>();
For<ILogger>().Use<Logger>();
//what to do for IMappingEngine?
}
}
我想加载的个人资料
public class MyAutoMapperProfile : AutoMapper.Profile
{
protected override void Configure()
{
this.CreateMap<MyModel, MyDTO>();
}
}
推荐答案
Mapper
class有一个静态属性 Mapper.Engine
。使用它来注册引擎与容器:
The Mapper
class has a static property Mapper.Engine
. Use this to register the engine with the container:
For<IMappingEngine>().Use(() => Mapper.Engine);
如果您需要在注册引擎之前加载您的配置文件,我将在上面的代码段中插入配置代码。
If you need to load your profiles before injecting the engine I would insert that configuration code alongside the above snippet.
更新
您的自定义注册表将如下所示
Your custom registry would look like this
class MyRegistry : Registry
{
public MyRegistry()
{
For<IMyRepository>().Use<MyRepository>();
For<ILogger>().Use<Logger>();
Mapper.AddProfile(new AutoMapperProfile());
For<IMappingEngine>().Use(() => Mapper.Engine);
}
}
此代码在您的引导程序中运行一次,键入 IMappingEngine
将以静态属性 Mapper.Engine
的值提供,它使用您的自定义 AutoMapperProfile
。
This code runs once in your bootstrapper and any dependency of type IMappingEngine
will afterwards be served with the value of the static property Mapper.Engine
which is configured using your custom AutoMapperProfile
.
这篇关于如何使用StructureMap注入AutoMapper IMappingEngine的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!