Eth*_*fer 13 .net autofac automapper
我已经在.Net应用程序中使用Automapper和Autofac一段时间了.我这样配置它们:
builder.RegisterAssemblyTypes(typeof (OneOfMyMappingProfiles).Assembly)
.Where(t => t.IsSubclassOf(typeof (Profile)))
.As<Profile>();
builder.Register(ctx => new ConfigurationStore(new TypeMapFactory(), MapperRegistry.Mappers))
.AsImplementedInterfaces()
.SingleInstance()
.OnActivating(x =>
{
foreach (var profile in x.Context.Resolve<IEnumerable<Profile>>())
{
x.Instance.AddProfile(profile);
}
});
builder.RegisterType<MappingEngine>()
.As<IMappingEngine>().SingleInstance();
Run Code Online (Sandbox Code Playgroud)
使用最新版本的Automapper(4.2),API已发生变化,我无法转换为新的API.ConfigurationStore似乎不再存在.根据文档,注册IOC的方式现在是这样的:
var profiles =
from t in typeof (AutoMapperRegistry).Assembly.GetTypes()
where typeof (Profile).IsAssignableFrom(t)
select (Profile)Activator.CreateInstance(t);
var config = new MapperConfiguration(cfg =>
{
foreach (var profile in profiles)
{
cfg.AddProfile(profile);
}
});
For<MapperConfiguration>().Use(config);
For<IMapper>().Use(ctx => ctx.GetInstance<MapperConfiguration>().CreateMapper(ctx.GetInstance));
Run Code Online (Sandbox Code Playgroud)
但是那是使用StructureMap.上半部分没有问题,但我不知道如何翻译"For <>.Use()"部分.我如何在Autofac中做到这一点?
Eth*_*fer 21
好.解决了这个问题.这是替代品:
var profiles =
from t in typeof(LocationMappingProfile).Assembly.GetTypes()
where typeof(Profile).IsAssignableFrom(t)
select (Profile)Activator.CreateInstance(t);
builder.Register(ctx => new MapperConfiguration(cfg =>
{
foreach (var profile in profiles)
{
cfg.AddProfile(profile);
}
}));
builder.Register(ctx => ctx.Resolve<MapperConfiguration>().CreateMapper()).As<IMapper>();
Run Code Online (Sandbox Code Playgroud)
UPDATE
这是一个配置文件的示例.超级简单.在这种情况下,我只有一个映射.但我可以添加其他人.我尝试通过实体将它们逻辑地保持在一起.因此,在这种情况下,从ProviderDetail到ProviderDetail的任何未来映射都将在此文件中.映射到不同的实体将位于单独的mappingprofile类中.配置文件类中没有注入任何内容:
public class ProviderMappingProfile : Profile
{
protected override void Configure()
{
CreateMap<ProviderDetail, ProviderListItem>();
}
}
Run Code Online (Sandbox Code Playgroud)
UPDATE2
以下是一个测试示例,证明映射是正确的:
public class ProviderMappingProfileTests
{
[Fact]
public void CreateMap_ProviderDetailToProviderQueryResult_IsValid()
{
var config = new MapperConfiguration(cfg =>
cfg.CreateMap<ProviderDetail, ProviderListItem>()
);
config.AssertConfigurationIsValid();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9473 次 |
| 最近记录: |