dotnet / dotnet/MQTTnet

Access to database when get message from MQTT in .net 6

Open
#1,632 3 comments 0 reactions 0 assignees View on GitHub
question
Dominant language
C#
Stars
5.1k
Forks
1.2k
PR merge metrics
No merged PRs in 30d

Description

I use MQTT in my WebAPI project (.net 6) and need to check in the database when get message from MQTT, but can't and occur error

> Cannot access a disposed context instance. A common cause of this
> error is disposing a context instance that was resolved from
> dependency injection and then later trying to use the same context
> instance elsewhere in your application. This may occur if you are
> calling 'Dispose' on the context instance, or wrapping it in a using
> statement. If you are using dependency injection, you should let the
> dependency injection container take care of disposing context
> instances. Object name: 'DatabaseContext

I use dependency injection and UnitOFWork

Program.cs

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddDbContext(options => options.UseSqlServer(builder.Configuration.GetSection("ConnectionStrings").GetSection(environment).Value));
builder.Services.AddTransient();
builder.Services.AddTransient();
builder.Services.AddEndpointsApiExplorer();
var app = builder.Build();

MQTTCheck(app);

app.MapControllers();
app.Run();

void MQTTCheck(IHost app)
{
var scopedFactory = app.Services.GetService();
using (var scope = scopedFactory.CreateScope())
{
var service = scope.ServiceProvider.GetService();
service.check();
}
}

MQTTManager.cs:

public class MQTTManager
{
IMqttClient client;
readonly IUnitOfWork _uow;

string serverAddress = "XXXXXX";
int port = 1883;

public MQTTManager(IUnitOfWork uow)
{
_uow = uow;
}

public async void check()
{
try
{
client = new MqttFactory().CreateMqttClient();
var options = new MqttClientOptionsBuilder()
.WithClientId(Guid.NewGuid().ToString())
.WithTcpServer(serverAddress, port)
.WithCleanSession()
.WithWillRetain(false)
.Build();

client.ApplicationMessageReceivedAsync += Client_ApplicationMessageReceivedAsync;

await client.ConnectAsync(options);
}
catch (Exception ex){}
}

private Task Client_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs x)
{
string topic = x.ApplicationMessage.Topic;
string receiveMsg = x.ApplicationMessage.ConvertPayloadToString();

Home home = _uow.HomeRepository.Get(h => h.Name == topic);
//...

return Task.CompletedTask;
}

}

The error occurs in this line:

Home home = _uow.HomeRepository.Get(h => h.Name == topic);

For example in windows form application when I want to access controls on the form in MQTT receive message event should use this pattern

this.BeginInvoke((MethodInvoker)delegate { label1.Text = "Disconnected"; });

I think that I should use something like this!

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.