无法从单例yyy中使用作用域服务xxx [英] Cannot consume scoped service xxx from singleton yyy
问题描述
我关注了一篇博客文章使用ASP.NET Core和Visual Studio Code构建您的第一个Web API。
I followed a blog post for 'Building Your First Web API with ASP.NET Core and Visual Studio Code'.
http://www.codingflow.net/building-your-first-web-api-with-asp-net-core-and-visual-studio-code/
在这种情况下,数据不会像这样保存在数据库中,而是保存在内存中:
In this scenario, data are not saved in database but rather in memory like this:
services.AddDbContext<TodoContext>(options => options.UseInMemoryDatabase());
services.AddSingleton<ITodoRepository, TodoRepository>();
您会注意到:
(1 ) UseInMemoryDatabase
在 DbContext
(2)<$ TodoRepository
上的c $ c> AddSingleton 效果很好。现在,我更新了代码以将数据保存在真实数据库中。因此,主要的更改是:
This works pretty well. Now I updated the code to save data inside a real database. So main changes are:
services.AddDbContext<TodoContext> (options => options.UseSqlite("Data Source=blogging.db"));
services.AddSingleton<ITodoRepository, TodoRepository>();
我想通知我,我不得不迁移 AspNetCore
从1.0到2.2。
I would like to notify that I had to migrate AspNetCore
from 1.0 to 2.2.
现在在运行时,将控制器作为目标时,出现错误:无法从单例'Models.ITodoRepository'中使用作用域服务'Models.TodoContext'。 / strong>
Now at runtime, when targetting the controller, I got the error: Cannot consume scoped service 'Models.TodoContext' from singleton 'Models.ITodoRepository'.
我了解在这种情况下:
-
我的
TodoContext
是一个范围对象:请求中相同,但不同请求中不同。
My
TodoContext
is a Scoped object: the same within a request, but different across different requests.
我的 TodoRepository
是一个Singleton对象:每个对象和每个请求都相同。
My TodoRepository
is a Singleton object: the same for every object and every request.
因此,我终于将 AddSingleton
更改为 AddScoped
,它的效果很好:
So I finally changed AddSingleton
to AddScoped
which works pretty fine:
services.AddDbContext<TodoContext> (options => options.UseSqlite("Data Source=blogging.db"));
services.AddScoped<ITodoRepository, TodoRepository>();
我的问题是:要知道这是否可以接受?
My question is: to know whether of not this is an acceptable approach ?
PS:我知道关于SO的这个问题还有其他问题,但是我没有清楚的回答。
PS: I know there are other questions on this issue on SO but I didn't read clear response.
推荐答案
对于您的问题,是的,这是正确的处理方法。
For your question, yes it is the right way to do the things.
我想总结一下答案更好的方法,但是后来我对此主题进行了研究,发现一篇文章,用于处理您所询问的问题。
I wanted to summarize the answer in a better way, but then I did some research on this topic and I found an article that deals with questions like you asked.
我建议您看一下该文章,因为它具有 最佳做法部分,介绍如何解决某些问题。
I would suggest having a look at the article since it has "Best Practices" sections on how to approach certain problems.
这篇关于无法从单例yyy中使用作用域服务xxx的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!