Search code examples
c#dependency-injectiondispose

How resource is disposed when registered as services.AddSingleton but initiated with a using block


I am using .NET Core 3.1.

I have a simple publish class which purpose is to publish messages to a message broker. All the logic for the message broker is in a separate class library and the publish class itself need somehow to get a connection in order to publish the message, so it looks like that:

 public class Publisher : IPublisher
 {
    public void Publish(string subject, PublishMessage message)
    {
        var options = ConnectionFactory.GetDefaultOptions();

        using (var connection = new ConnectionFactory().CreateEncodedConnection(options))
        {
            connection.OnSerialize = jsonSerializer;
            connection.Publish(subject, message);
            connection.Flush();
        }
    }
 }

By the way new ConnectionFactory().CreateEncodedConnection(options) is native for the message broker so this is not a wrapper written by me.

However. In my web project I register this in the DI like this:

services.AddSingleton<IPublisher, Publisher>();

My final goal is to share the same connection, I know that when the times comes the DI will dispose all disposable resources but since I wrap the connection in a using block does it always dispose the connection and create a new one for each message or the DI manages to handle this somehow. And if not, how can I make is to the connection is not created for each message?


Solution

  • services.AddSingleton<IPublisher, Publisher>(); Create instance of Publisher class when application starts, but connection will be created and disposed every time you calls Publish method.