25

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

4

1 回答 1

30

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

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

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

于 2012-08-12T11:56:20.513 回答