Reputation: 125
I have created application in .net core 3.1, In which there are one singleton interface and its implementation class, which is receiving the TCP/IP socket message. There is one event handler in the class, which will be invoked once messages received on the socket.
public Class IncomingMessageHandler : IIncomingMessageHandler { public event EventHandler<string> OnMessageReceived; private void InvokeMessageRecived(object sender, string message) { this.OnMessageReceived?.Invoke(this, message); } }
There is one another service TransactionService
class which is having dependency injected for the interface IIncomingMessageHandler
and subscribe to OnMessageReceived
.
public TransactionService(IIncomingMessageHandler incomingMessageHandler) { this.incomingMessageHandler = incomingMessageHandler; this.incomingMessageHandler.OnMessageReceived += this.IncomingMessageHandler_OnMessageReceived; }
From this class, I am initiating the transaction and once a transaction started I will receive the messages into IncomingMessageHandler
and OnMessageReceived
invokes, Messages I am storing into the List for further processing.
Now TransactionService
is the Scoped service class and for each API request new object will be created, Now If there are multiple requests are made, for each TransactionService
would subscribe to OnMessageReceived
and it invokes multiple time because there are multiple objects initiated and override the List of messages.
I can't register TransactionService
as singleton due to some other limitations.
Is there any other way through which OnMessageReceived
gets invoked only for the specific service object?
I have tried to un-subscribe the OnMessageReceived
, but still, this issue will occur for multiple API requests at the same time.
Upvotes: 1
Views: 1940
Reputation: 190945
Since you are binding to an event and not unbinding when finished, it causes a bit of a memory leak - the instances of TransactionService
live on in other references and can't be GC'd. You should have TransactionService
implement IDisposable
and unbind it in the Dispose
method. That removes the reference from the event in IncomingMessageHandler
and you won't have duplicate calls.
Aside: I tried something very similar and I actually found using Reactive Extensions made for a much better pattern overall.
Upvotes: 0