设置
我有一个AutoMapperConfiguration静态类来设置AutoMapper映射:
static class AutoMapperConfiguration()
{
internal static void SetupMappings()
{
Mapper.CreateMap<long, Category>.ConvertUsing<IdToEntityConverter<Category>>();
}
}其中IdToEntityConverter<T>是一个自定义ITypeConverter,如下所示:
class IdToEntityConverter<T> : ITypeConverter<long, T> where T : Entity
{
private readonly IRepository _repo;
public IdToEntityConverter(IRepository repo)
{
_repo = repo;
}
public T Convert(ResolutionContext context)
{
return _repo.GetSingle<T>(context.SourceValue);
}
}IdToEntityConverter在其构造函数中接受一个IRepository,以便通过访问数据库将ID转换回实际实体。注意它是如何没有默认构造函数的。
在我的ASP.NET的Global.asax中,这就是我为OnApplicationStarted()和CreateKernel()所拥有的
protected override void OnApplicationStarted()
{
// stuff that's required by MVC
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
// our setup stuff
AutoMapperConfiguration.SetupMappings();
}
protected override IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<IRepository>().To<NHibRepository>();
return kernel;
}因此,OnApplicationCreated()将调用AutoMapperConfiguration.SetupMappings()来设置映射,CreateKernel()将将NHibRepository的一个实例绑定到IRepository接口。
问题
每当我运行这段代码并试图让AutoMapper将一个类别ID转换回一个类别实体时,我就会得到一个AutoMapperMappingException,它说明IdToEntityConverter上不存在默认构造函数。
尝试
IdToEntityConverter添加了默认构造函数。现在我得到一个NullReferenceException,它向我表明注入不是NullReferenceException--私有_repo字段进入公共属性,并添加了[Inject]属性。仍然在接受NullReferenceException.[Inject]属性。虽然NullReferenceException.OnApplicationStarted()中的AutoMapperConfiguration.SetupMappings()调用,但我还是把它移到了一个我知道的正确注入控制器上,比如:公共类RepositoryController :控制器{静态RepositoryController() { AutoMapperConfiguration.SetupMappings();}
还能得到NullReferenceException.
问题
我的问题是,我如何让Ninject将一个IRepository注入到IdToEntityConverter
发布于 2010-11-02 04:25:40
您必须授予AutoMapper对DI容器的访问权限。我们使用StructureMap,但我想下面的内容应该适用于任何DI。
我们使用这个(在我们的Bootstrapper任务中)。
private IContainer _container; //Structuremap container
Mapper.Initialize(map =>
{
map.ConstructServicesUsing(_container.GetInstance);
map.AddProfile<MyMapperProfile>();
}发布于 2012-04-25 15:51:06
@ozczecho的答案是点对点的,但我现在贴出了while版本的代码,因为它有一个小小的警告,让我们有一段时间没注意到:
IKernel kernel = null; // Make sure your kernel is initialized here
Mapper.Initialize(map =>
{
map.ConstructServicesUsing(t => kernel.Get(t));
});您不能只将kernel.Get传递给map.ConstructServicesUsing,因为该方法除了类型之外还有一个params参数。但是由于params是可选的,所以您可以创建lambda表达式来生成一个匿名函数来获得所需的内容。
https://stackoverflow.com/questions/4074609
复制相似问题