I have implemented WebSocket middleware who has contains as a field singleton WebSocket dictionary(injected via constructor) and some other scoped parameters injected via constructor.
I would like to know if it's implemented correctly.
public WebSocketManagerMiddleware(RequestDelegate next,
IWebSocketConnectionDictionary webSocketDictionary,
IScopedServiceOne scopedOneService, IScopedServiceTwo scopedtwoService)
{
_next = next;
_webSocketManager = webSocketDictionary;
_scopedOneService= scopedOneService;
_scopedtwoService= scopedtwoService;
}
To this constructor, I am injecting these instances like this:
_app.UseMiddleware<WebSocketManagerMiddleware>(
app.ApplicationServices.GetWebSocketConnectionDictionary(),
serviceProvider.CreateScope().ServiceProvider.GetScopedOneService(),
serviceProvider.CreateScope().ServiceProvider.GetScopedTwoService())
I am afraid that I every time on WebSocket request create new scope from where I am getting scoped services(serviceOne, serviceTwo) and it never disposed until WebSocket connection is closed. Because I am using these services only on the websocket start and after I starting to listen to upcoming messages I never use them (IScopedOneSerice, IScopedTwoService)
public async Task Invoke(HttpContext context, IServiceProvider service)
{
await _scopedOneService.MethodOne();
await _scopedTwoService.MethodTwo();
//startint to listen for messages and if I need to call some repository
// method I am using
//IServiceProvider, i.e ISomeRepository repo =
// service.GetRequiredService<ISomeRepository>(); // this repo scoped as well
}
Is it possible to get any memory leak this way?
UPDATED: What I am trying to achieve: let's make it simple, every time I get a websocket message I need to insert the message to the repository or resolve some other services who communicates with other business logic services.
I am not sure what is the best approach to inject scoped serviecs into websocket middleware who contains singleton websocket dictionary and some other scoped services.