var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<SomeSourceModel, SomeDestinationModel>();
});
config.AssertConfigurationIsValid();
var mapper = config.CreateMapper();
我在项目中重复这些代码。想创建一个通用接口 IMapper 以便我可以在需要使用时调用。
我创建的解决方案是
private IMapper Mapper(TSource source, TDestination dest)
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<source, dest>();
});
config.AssertConfigurationIsValid();
return config.CreateMapper();
}
它不起作用。问题是我无法以这种方式将源模型和目标模型作为参数传递。如何解决这个问题?
更新 1:
正如@12秒提到的,我开始初始化MapperConfigration
中Global.asax.cs
在 App_Start 文件夹中,我创建了
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<SourceModel1, DestinationModel1>();
CreateMap<SourceModel2, DestinationModel2>();
CreateMap<SourceModel3, DestinationModel3>();
CreateMap<SourceModel4, DestinationModel4>();
CreateMap<SourceModel5, DestinationModel5>();
Mapper.AssertConfigurationIsValid();
}
}
在 Global.asax.cs
public class AutoMapperConfiguration
{
public static void Configure()
{
Mapper.Initialize(x =>
{
x.AddProfile<MappingProfile>();
});
}
}
然后我试着AutoMapperConfiguration.Configure();
在几个地方打电话。当我开始运行应用程序时,我收到了相同的错误消息:
映射器未初始化。使用适当的配置调用 Initialize。如果您尝试通过容器或其他方式使用映射器实例,请确保您没有对静态 Mapper.Map 方法的任何调用,并且如果您使用的是 ProjectTo 或 UseAsDataSource 扩展方法,请确保您传入适当的 IConfigurationProvider实例。
我想在哪里打电话AutoMapperConfiguration.Configure();
?我错过了什么?
问题解决了。Mapper.AssertConfigurationIsValid();
应该在 Mapper 初始化后执行。
public class AutoMapperConfiguration
{
public static void Configure()
{
Mapper.Initialize(x =>
{
x.AddProfile<MappingProfile>();
});
Mapper.Configuration.AssertConfigurationIsValid();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句