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

标签 asp.net-mvc ninject telerik-open-access

我第一次尝试使用 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 绑定(bind)的样子..
kernel.Bind<ContentService>().To<ContentService>().InRequestScope();
kernel.Bind<IContentRepository>().To<ContentRepository>().InRequestScope().WithConstructorArgument("_db", new DBContext());

如果我一次取一页,一切正常。我正在使用一个简单的工具“XENU”同时获取多个页面。这是当我一次获取多个页面时出现 DBContext 错误的时候。

我不确定 Ninject 是否在每个 REQUEST 中添加 DBContext?我得到不同的错误,例如'对象引用未设置为对象的实例。',或'ExecuteReader 需要打开且可用的连接。连接的当前状态是打开的。

附言

我的 MVC Web 应用程序的文件夹下有 ContentService。 ContentRepository 是一个单独的程序集。我将在 ContentService 中添加业务逻辑,并将“ContentRepository”仅用于 CRUD 操作。另外,请让我知道这种架构是否可以,或者是否有更好的方法来创建服务和存储库。

最佳答案

以下是我将如何做你的 Ninject 绑定(bind),

kernel.Bind<DBContext>().ToSelf().InRequestScope();
kernel.Bind<ContentService>().ToSelf().InRequestScope();
kernel.Bind<IContentRepository>().To<ContentRepository>().InRequestScope();

这种模式在上面的例子中使用 EF 和 Ninject 应该可以正常工作。

关于asp.net-mvc - 使用 Ninject 时如何处理 DBContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11921883/

相关文章:

ninject - NserviceBus启动事件

c# - 使用 Telerik openAcces ORM 从 mysql 服务器获取数据并将其上传到 Sql 服务器

entity-framework - 我们如何从 Telerik Open Access 切换到其他任何东西?

c# - 你如何根据用户交替 Ninject 绑定(bind)?

c# - 使用 Ninject 的 WCF 服务问题(从 Windsor 移动)(InvalidOperationException)

c# - 使用 telerik openacces ORM 创建成员(member)资格和

javascript - 检测与 JQuery 数据表的交互

asp.net-mvc - 在 MVC3 中使用 jQuery DataTables 插件和 jQuery Ajax

asp.net-mvc - 如果我想将 View 分解为更小的 subview ,我应该在 ASP.NET MVC 中创建什么项目?

asp.net-mvc - asp.net mvc 和身份验证示例