我正在使用 .NET Core 2.1 和 Entity Framework 制作一个 n 层 MVC 应用程序。还有一个托管的 MQTT 队列,我的应用程序在该队列上作为客户端进行侦听。我还使用依赖注入。这非常有效,直到一条消息被推送到队列并且我想将该消息保存到数据库。一旦发生这种情况,我会收到以下ObjectDisposedException错误消息:
无法访问已处置的对象。此错误的一个常见原因是处理从依赖项注入解析的上下文,然后尝试在应用程序的其他地方使用相同的上下文实例。如果您在上下文中调用 Dispose() 或将上下文包装在 using 语句中,则可能会发生这种情况。如果您正在使用依赖注入,则应该让依赖注入容器负责处理上下文实例。对象名称:'xxxDbContext'。
我可以单击继续,之后应用程序继续工作。他只在从队列收到的第一条消息上抛出异常。控制器/管理器/存储库的所有其他操作都可以正常工作。我的代码如下:
启动.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDefaultIdentity<User>()
.AddEntityFrameworkStores<xxxDbContext>();
services.AddDbContext<xxxDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")
));
// Some identity configuration omitted here
services.AddScoped<IIdeationRepository, IdeationRepository>();
services.AddScoped<IIdeationManager, IdeationManager>();
// Some other DI configuration omitted as well.
}
public Configure(IApplicationBuilder app, IHostingEnvironment env,
IApplicationLifetime applicationLifetime, IServiceProvider serviceProvider)
{
// Start MQTT
var broker = new MqttBroker(serviceProvider.GetService<IIdeationManager>(),
serviceProvider.GetService<IConfiguration>());
// On application exit terminate MQTT to make sure the connection is ended properly
applicationLifetime.ApplicationStopping.Register(() => broker.Terminate());
// Some default http pipeline code omitted
}
MqttBroker.cs
public MqttBroker(
[FromServices] IIdeationManager ideationManage,
[FromServices] IConfiguration configuration)
{
_ideationManager = ideationManager;
_configuration = configuration;
Initialize();
}
// Some code where I just parse the message and on receive send it to the
// ideation manager, this just works so I omitted it.
}
管理器只是将它直接发送到出现错误消息的存储库。
慕容3067478
慕村225694
相关分类