我不太清楚如何将以下结构映射实现转换为 unity。
public AutoMapperRegistry()
{
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));
}
遇到了同样的问题,终于通过执行以下操作使其正常工作
var configuration = new MapperConfiguration(x =>
{
//Your configuration for your mapper
});
var mapper = configuration.CreateMapper();
container.RegisterInstance(mapper);
我最终使用以下扩展方法
public static IUnityContainer RegisterMapper(this IUnityContainer container)
{
return container
.RegisterType<MapperConfiguration>(new ContainerControlledLifetimeManager(), new InjectionFactory(c =>
new MapperConfiguration(configuration =>
{
configuration.ConstructServicesUsing(t => container.Resolve(t));
foreach (var profile in c.ResolveAll<Profile>())
configuration.AddProfile(profile);
})))
.RegisterType<IConfigurationProvider>(new ContainerControlledLifetimeManager(), new InjectionFactory(c => c.Resolve<MapperConfiguration>()))
.RegisterType<IMapper>(new InjectionFactory(c => c.Resolve<MapperConfiguration>().CreateMapper()));
}
和
public static IUnityContainer RegisterMappingProfile<T>(this IUnityContainer container)
where T : Profile
{
return RegisterMappingProfile(container, typeof(T));
}
在我的 Unity 容器配置类中,我调用它们
container.RegisterMapper();
container.RegisterMappingProfile<WebProfile>();