在ASP.NET Core中创建范围工厂

编程入门 行业动态 更新时间:2024-10-25 19:25:32
本文介绍了在ASP.NET Core中创建范围工厂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在asp核心中创建作用域容器,并在我的singleton方法的2种方法中使用它。

I want to create scoped container in asp core and use it in 2 methods of my singleton method.

我尝试在sigleton的每种方法中创建此容器。

I've tried create this in each method of sigleton. it works, but i think it is overhead.

var scopeFactory = _serviceProvider.GetService<IServiceScopeFactory>(); var scope = scopeFactory.CreateScope(); var scopedContainer = scope.ServiceProvider;

我在需要时用每种方法编写它。我认为这是逻辑错误。请给我解释一下如何正确执行?谢谢

I write it in each method when i need it. I think it is logic mistake. Please, explain me how to do it correct? thank you

推荐答案

从技术上讲,这不是错误的操作方式。如果您位于单例服务中,并且需要访问作用域服务,则应该创建一个新的服务范围,并从该范围的服务提供者那里检索服务。完成后,您还应该配置范围。

It is technically not incorrect the way you do it. If you are within a singleton service and you need to access scoped services, then you should create a new service scope and retrieve the services from that scope’s service provider. And when you are done, you should also dispose the scope.

在实践中,您可以对此进行一些简化。您应该避免将 IServiceProvider 直接注入服务中。相反,您可以直接注入 IServiceScopeFactory 。然后,您还应该使用 using 语句创建作用域,以确保在使用后将其正确处置。

In practice, you can simplify this a bit. You should avoid having to inject IServiceProvider directly into a service. Instead, you can just inject the IServiceScopeFactory directly. And then you should also create the scope with a using statement to make sure that it is disposed properly after use.

因此,单例服务示例如下所示:

So an example singleton service could look like this:

public class ExampleSingletonService { private readonly IServiceScopeFactory _serviceScopeFactory; public ExampleSingletonService(IServiceScopeFactory serviceScopeFactory) { _serviceScopeFactory = serviceScopeFactory; } public async Task DoSomethingAsync() { using (var scope = _serviceScopeFactory.CreateScope()) { var db = scope.ServiceProvider.GetService<MyDbContext>(); db.Add(new Foo()); await db.SaveChangesAsync(); } } }

如您所见,确实不是很多 。但这当然会让您三思而后行,是否要在单个实例中使用作用域服务。

As you can see, there isn’t really that much overhead for this. But of course this makes you think twice about whether you want to use a scoped service within a singleton or not.

更多推荐

在ASP.NET Core中创建范围工厂

本文发布于:2023-11-17 03:30:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1608659.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:工厂   ASP   NET   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!