ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

在给定的请求实例中使用依赖注入的DbContext是否在所有使用它的类之间共享?

2019-11-11 06:06:24  阅读:237  来源: 互联网

标签:dependency-injection ninject c asp-net-mvc entity-framework


我想知道Ninject在以下情况下到底如何处理EF DbContext注入.

有一个实用程序类,它将DbContext作为参数,并执行一些需要dbContext的工作:

public class SomeClass : ISomeClass
{
    public SomeClass(MyDbContext context)
    {
        //the context is dependency injected
    }
}

有一个采用DbContext的API控制器以及一个ISomeClass的注入实例(这也需要DbContext)

    public class SomeController
    {

        public SomeController(MyDbContext context, ISomeClass someClass)
        {
            //this controller uses db context for some simple actions and someclass for some more complex actions
        }
    }

绑定选项设置为:

kernel.Bind< MyDbContext>().ToSelf().InRequestScope();

现在的问题是

实例化SomeController时,SomeClass的实例是否共享MyDbContext的相同实例?
另外,如果SomeClass注入了SomeSubClass,而MyDbContext也注入了构造函数,那将是同一上下文实例吗?

它是这样工作的吗?

An http request comes in and requires creating controller and its
dependencies that require DbContext, so since we are set to
InRequestScope, lets return the same instance to rule them all?

如果是这样,则控制器构造器之间没有区别(明智的DbContext),该构造器接受上下文并像这样创建UnitOfWork类(pattern from here)

public class SomeController(MyDbContext context)
{
   this.someUnitOfWork = new SomeUnitOfWork(context);
}

还有一个将工作单位作为注入参数

public class SomeController(MyDbContext context, ISomeUnitOfWork someUnit){}

在这里,唯一的区别是与SomeUnitOfWork实现的紧密结合吗?

解决方法:

An http request comes in and requires creating controller and its
dependencies that require DbContext, so since we are set to
InRequestScope, lets return the same instance to rule them all?

是.这就是InRequestScope所做的.

https://github.com/ninject/Ninject.Web.Common/wiki/InRequestScope具有所有有趣的细节:

The main reason for using InRequestScope() is to make sure that a
single instance of an object is shared by all objects created via the
Ninject kernel for that HTTP request (e.g. to share an object that is
expensive to create).

标签:dependency-injection,ninject,c,asp-net-mvc,entity-framework
来源: https://codeday.me/bug/20191111/2018018.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有