具有单例依赖注入的 Entity Framework Core

发布于 2025-01-17 13:37:30 字数 792 浏览 0 评论 0原文

我正在尝试将依赖注入与单例和 DBContext 一起使用。

在 .net 框架中,我可以执行类似的操作

public class MySingleton
{
    private readonly Func<MyDbContext> _getContext;
    public MySingleton(Func<MyDbContext> getContext)
    {
      _getContext = getContext;
    }
}

但是,当我现在执行此操作时,出现以下错误:

无法解析类型“System.Func`1[MyDbContext]”的服务

我确实尝试将其添加到构造函数中。

public class MySingleton
{
    private readonly Func<MyDbContext> _getContext;
    public MySingleton(IServiceProvider serviceProvider)
    {
         _getContext =
             () => (MyDbContext)serviceProvider.GetService(typeof(MyDbContext));
    }
}

但是,serviceProvider 返回相同的实例,

如何在每次使用 MyDbContext 时创建一个新实例?

I am trying to use Dependency Injection with a singleton and DBContext.

In .net framework I can do something like this

public class MySingleton
{
    private readonly Func<MyDbContext> _getContext;
    public MySingleton(Func<MyDbContext> getContext)
    {
      _getContext = getContext;
    }
}

However, when I do this now I get the following error:

Unable to resolve service for type 'System.Func`1[MyDbContext]'

I did try to add this to the constructor.

public class MySingleton
{
    private readonly Func<MyDbContext> _getContext;
    public MySingleton(IServiceProvider serviceProvider)
    {
         _getContext =
             () => (MyDbContext)serviceProvider.GetService(typeof(MyDbContext));
    }
}

However, serviceProvider returns the same instance

How can I create a new instance of MyDbContext every time I use it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

您的好友蓝忘机已上羡 2025-01-24 13:37:30

当用女士解析单身人士时,Singleton 及其所有依赖项都是从根范围/容器中解析的。这就是为什么您会体验从注射iserviceProvider始终给出相同实例的行为的行为。该范围的实例范围为容器。换句话说,这个范围的实例隐含成为单身人士。

女士di的封闭构图模型使得很难在单例内解决范围通过环境状态手动管理范围),因为使用环境组成模型

实际上,这里有两个选择:

  1. 要么您要么将单顿组件的生活方式缩短到transient> transient scoped
  2. 您启动并管理iservicescope从组件的方法内部从该范围中解析范围内的组件。例如:
     公共类mysingleton
    {
        私人Readonly IserviceProvider提供商;
        公共Mysingleton(IserviceProvider提供商)
        {
            this.provider =提供商;
        }
    
        公共无效的somemethod()
        {
            使用(var scope = this.provider.createscope())
            {
                scope.ServiceProvider.getRequiredInstancce&lt; mydbcontext&gt;();
            }
        }
    }
     

When resolving a singleton with MS.DI, that singleton and all its dependencies are resolved from the root scope/container. This is why you experience the behavior where resolving the MyDbContext from an injected IServiceProvider always gives the same instance; that scoped instance is scoped to the container. In other words, that scoped instance implicitly became a singleton.

MS.DI's Closure Composition Model makes it very hard to resolve scopes within singletons (without manually managing scopes through ambient state), because scopes are not available ubiquitously through ambient state, as is done using the Ambient Composition Model.

In practice, there are two options here:

  1. Either you shorten the lifestyle of your singleton component to either Transient or Scoped
  2. You start and manage an IServiceScope from within the component's methods and resolve the scoped component from such scope. For instance:
    public class MySingleton
    {
        private readonly IServiceProvider provider;
        public MySingleton(IServiceProvider provider)
        {
            this.provider = provider;
        }
    
        public void SomeMethod()
        {
            using (var scope = this.provider.CreateScope())
            {
                scope.ServiceProvider.GetRequiredInstancce<MyDbContext>();
            }
        }
    }
    
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文