当您尝试通过容器创建对象时,它Ninject
崩溃了exception
:Object reference not set to an instance of an object.
请告诉我,可能是什么问题?
来自类的方法NinjectDependencyResolver
private void AddBindings()
{
var mapperConfiguration = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new TagProfile());
});
var mapper = mapperConfiguration.CreateMapper();
_kernel.Bind<BlogDbContext>().ToSelf().InRequestScope();
_kernel.Bind<IRepository<Tag>, Repository<Tag>>();
_kernel.Bind<IMapper>().ToConstant(mapper);
var repository = _kernel.Get<IRepository<Tag>>();// вылетает exception
_kernel.Bind<ITagService, TagService>();
}
存储库类
public class Repository<T> : IRepository<T> where T : class
{
private readonly BlogDbContext _db;
public Repository(BlogDbContext db)
{
_db = db;
}
}
PS我不知道这是否重要,但是带有接口的存储库在一个程序集中,而注册Ninject
在另一个程序集中。
该错误表示未在对象实例中设置对象引用。
在这两行
你“告诉”IoC 容器当你请求
IRepository<Tag>
or时Repository<Tag>
,你需要返回一个实现,但你没有指定一个。下一个调用是正确的。
您是在告诉 IoC 容器
IRepository<Tag>
创建Repository<Tag>
. 对于第二行,它是相似的。以及评论中问题的答案:
对于 Repository 和 Service 不需要做
InRequestScope()
,只为 contextBlogDbContext
更新程序
没关系,主要是指定一个链接到存储库和接口所在的程序集