【发布时间】:2010-11-02 02:54:32
【问题描述】:
设置
我有一个设置 AutoMapper 映射的 AutoMapperConfiguration 静态类:
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,它向我表明注入不起作用。将私有
_repo字段设为公共属性并添加[Inject]属性。仍然收到NullReferenceException。在采用
IRepository的构造函数上添加了[Inject]属性。仍然收到NullReferenceException。-
考虑到 Ninject 可能无法拦截
OnApplicationStarted()中的AutoMapperConfiguration.SetupMappings()调用,我将其移至我知道正确注入的东西上,即我的控制器之一,如下所示:public class RepositoryController : Controller { static RepositoryController() { AutoMapperConfiguration.SetupMappings(); } }仍然收到
NullReferenceException。
问题
我的问题是,如何让 Ninject 将 IRepository 注入 IdToEntityConverter?
【问题讨论】:
标签: c# dependency-injection inversion-of-control ninject automapper