[英]Singleton with DbContext - creating instance in Startup.cs
I am using ASP.net core. 我正在使用ASP.net核心。 I have problem with implementing dbcontext into singleton.
我有将dbcontext实现为singleton的问题。
I need my singleton IModuleRepository to be running right after start of the project. 我需要在项目启动后立即运行我的单例IModuleRepository。 So I am creating new instance of this dependency in
public void ConfigureServices(IServiceCollection services)
in Startup.cs
file. 所以我在
Startup.cs
文件中的public void ConfigureServices(IServiceCollection services)
中创建了这个依赖项的新实例。
This singleton is using another singleton, so I am using it like this: 这个单身人士正在使用另一个单身人士,所以我这样使用它:
services.AddDbContext<ModulesDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")).EnableSensitiveDataLogging());
...
services.AddSingleton<IModuleRepository, ModuleRepository>();
services.AddSingleton<ICommunicationRepository>(new CommunicationRepository(services.BuildServiceProvider().GetService<IModuleRepository>()));
In ModuleRepository I am using DBcontext. 在ModuleRepository中我使用的是DBcontext。
// Db context
private readonly ModulesDbContext _modulesDbContext;
public ModuleRepository(ModulesDbContext modulesDbContext)
{
_modulesDbContext = modulesDbContext;
}
When I am calling _modulesDbContext.SomeModel.ToList();
当我调用
_modulesDbContext.SomeModel.ToList();
I get error: 我收到错误:
System.InvalidOperationException: An attempt was made to use the context while it is being configured.
System.InvalidOperationException:尝试在配置上下文时使用上下文。 A DbContext instance cannot be used inside OnConfiguring since it is still being configured at this point.
DbContext实例不能在OnConfiguring内使用,因为此时仍在配置它。
How to avoid this error when I need this singleton to run after the project is started? 如何在项目启动后需要运行此单例时避免此错误?
Thank you for your help. 谢谢您的帮助。
As @Ilya Chumakov commented, you could just tell the DI container to use your concrete class like so: 正如@Ilya Chumakov评论的那样,您可以告诉DI容器使用您的具体类,如下所示:
services.AddSingleton<ICommunicationRepository, CommunicationRepository>();
Then any class can depend on ICommunicationRepository
and get the concrete repository, which gets the Db context. 然后任何类都可以依赖于
ICommunicationRepository
并获取具体的存储库,它获取Db上下文。
I figured out this problem. 我想出了这个问题。 This calling of the dependencies were right.
这种依赖关系的调用是正确的。 The error is that in CommunicationRepository I've created 2 Task and both of them were using the same DbContext - so it was using it multiple times.
错误是在CommunicationRepository中我创建了2个Task,它们都使用了相同的DbContext - 所以它多次使用它。 I had to say
task.Wait();
我不得不说
task.Wait();
Full code in constructor of the CommunicationRepository after correction: 修正后CommunicationRepository的构造函数中的完整代码:
// Add pernament communication
var task = new Task(AddPernamentCommunicationAll);
task.Start();
task.Wait();
// Add modules
var taskModules = new Task(AddModulesToList);
taskModules.Start();
Thank you for your answers. 谢谢您的回答。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.