加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 使用Ninject时如何处理DBContext

发布时间:2020-12-16 00:26:23 所属栏目:asp.Net 来源:网络整理
导读:我试图第一次使用Ninject和OpenAccess。请帮我解决以下问题。这是我的项目看起来像… public class ContentController : Controller{ private ContentService contentSvc; public ContentController(ContentService contentSvc) { this.contentSvc = content
我试图第一次使用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?我得到不同的错误,例如’对象引用未设置为对象的实例’,OR’ExecuteReader需要一个打开和可用的连接。连接的当前状态是开放的。

附:

我在我的MVC网络应用程序的一个文件夹下有ContentService。 ContentRepository是一个单独的程序集。我将在ContentService中添加业务逻辑,并使用’ContentRepository’仅用于CRUD操作。另外,请让我知道这个架构是否可行,还是有更好的方式来创建服务和存储库。

解决方法

这是我将如何做你的Ninject绑定,
kernel.Bind<DBContext>().ToSelf().InRequestScope();
kernel.Bind<ContentService>().ToSelf().InRequestScope();
kernel.Bind<IContentRepository>().To<ContentRepository>().InRequestScope();

在上面的示例中,EF和Ninject可以正常工作。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读