简体   繁体   English

Wpf:在应用程序生命周期中使用单独的 dbcontext

[英]Wpf: using separate dbcontext in application lifetime

I have a wpf application with dependency injection.我有一个带有依赖注入的 wpf 应用程序。 I registered my context as service to use in app like below.我将我的上下文注册为要在应用程序中使用的服务,如下所示。

serviceCollection.AddDbContext<Context>(p => p.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));

I have another service that should fetch data from database every 15 seconds to check for new entities added and i do it with an event service and start the service in MainWindow.xaml startup and it goes to another thread.我有另一个服务应该每 15 秒从数据库中获取数据以检查添加的新实体,我使用事件服务执行此操作并在MainWindow.xaml启动中启动该服务,然后它转到另一个线程。

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    Task newOrdersTask = _eventService.SubscribeToNewOrders();
}

But sometimes while working with appplication i get this error.但有时在使用应用程序时我会收到此错误。

A second operation started on this context before a previous operation completed在前一个操作完成之前在此上下文上启动了第二个操作

How can i handle these scenarios?我该如何处理这些情况?

It is a bad idea to have a singleton DbContext in your entire application, especially when working on different threads is being considered.在整个应用程序中使用 singleton DbContext 是一个坏主意,尤其是在考虑使用不同线程时。

Passing ServiceLifetime.Transient as the second argument to AddDbContext will force creation of a new DbContext every time it gets injected by the container.ServiceLifetime.Transient作为第二个参数传递给AddDbContext将在每次被容器注入时强制创建一个新的 DbContext。 However, by doing so, you are going to miss a lot of features EF Core DbContext provides by default.但是,这样做会错过很多 EF Core DbContext 默认提供的功能。 You may consider implementing something like " ambient context pattern " to somehow preserve these features.您可以考虑实现类似“环境上下文模式”的东西以某种方式保留这些功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM