Is there a way to resolve a new scope per message? #17
Unanswered
justinpenguin45
asked this question in
Q&A
Replies: 1 comment 1 reply
-
You can. The consumer itself is a singleton, but it's a good idea to create a scope for each message using public class ConsumerService(IConsumer<byte[], byte[]> consumer, IServiceScopeFactory scopes) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
consumer.Subscribe("topic1");
while (true)
{
var result = consumer.Consume(stoppingToken);
using var scope = scopes.CreateScope();
var processor = scope.ServiceProvider.GetRequiredService<ConsumerProcessor>();
await processor.ProcessResult(result);
}
}
}
// Registered as scoped so you can inject other transient/scoped dependencies.
public class ConsumerProcessor
{
public Task ProcessResult(ConsumeResult<byte[], byte[]> result)
{
return Task.Delay(100);
}
} This is similar to the example in the DI documentation. I hope to add an implementation of |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
This would be analogous to asp.net core's scope per request lifetime?
Beta Was this translation helpful? Give feedback.
All reactions