我第一次尝试使用Ninject和OpenAccess。请帮我处理以下内容。这是我的项目的样子......
public class ContentController : Controller
{
private ContentService contentSvc;
public ContentController(ContentService contentSvc)
{
this.contentSvc = contentSvc;
}
}
以下课程位于我的网络应用程序的文件夹下。
public class ContentService
{
private IContentRepository contentRepository;
public ContentService(IContentRepository contentRepository)
{
this.contentRepository = contentRepository;
}
public void InsertContent(Content content)
{
contentRepository.InsertContent(content);
}
}
以下存储库属于单独的程序集。
public class ContentRepository : IContentRepository
{
DBContext db;
public ContentRepository(DBContext _db)
{
db = _db;
}
public void InsertContent(Content content)
{
db.Add(content);
}
}
这是Ninject绑定的样子..
kernel.Bind<ContentService>().To<ContentService>().InRequestScope();
kernel.Bind<IContentRepository>().To<ContentRepository>().InRequestScope().WithConstructorArgument("_db", new DBContext());
如果我一次取一页,一切正常。我正在使用一个简单的工具'XENU'来同时获取多个页面。这是当我通过一次获取多个页面而得到DBContext错误时。
我不确定Ninject是否在每个REQUEST中使用DBContext?我得到不同的错误,例如'对象引用未设置为对象的实例。',或'ExecuteReader需要一个开放且可用的连接。连接的当前状态是打开的。'
我在我的MVC网络应用程序中的文件夹下有ContentService。 ContentRepository是一个单独的程序集。我将在ContentService中添加业务逻辑,并仅将“ContentRepository”用于CRUD操作。另外,如果这个架构没问题,或者有更好的方法来创建服务和存储库,请告诉我。
答案 0 :(得分:27)
以下是我将如何进行Ninject绑定,
kernel.Bind<DBContext>().ToSelf().InRequestScope();
kernel.Bind<ContentService>().ToSelf().InRequestScope();
kernel.Bind<IContentRepository>().To<ContentRepository>().InRequestScope();
这个模式在上面的例子中应该可以正常使用EF和Ninject。