0

I'm trying to look for some samples for adding Azure "ServiceBusClient" as singleton using .NETFramework version 4.8. I couldn't find any resource link or sample code showcasing the way to do it.

Any help is appriciated!

Aryan
  • 374
  • 1
  • 2
  • 14
  • Have you added a DI framework in your .NET 4.8 application? It doesn't have it by default. (If you haven't, then the concept of adding it "as a singleton" doesn't really apply.) – ADyson Jun 29 '22 at 09:23
  • @ADyson, I don't have any idea on DI framework which can help me with this. Could you please suggest any of them? Also its an C# Windows Service Application which I'm trying to build. Most of the examples I found are targeting towards .NET CORE application and my application is not .NET CORE based. – Aryan Jun 29 '22 at 09:31
  • We don't do recommendations here, but there are several available as nuget packages. Alternatively, if you're not using it and don't need it in your app right now, just instantiate the service bus client in the normal way. It's not clear if that poses a problem for you or not. – ADyson Jun 29 '22 at 09:35
  • I'm able to instantiate the service bus client in normal way, but as per recommendation in this https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-performance-improvements?tabs=net-standard-sdk-2 article, it should be used as singleton instance, hence looking for some sample code to do so – Aryan Jun 29 '22 at 09:43
  • Simplest way is probably to add the Microsoft.Extensions.DependencyInjection namespace which gives you access to MS's DI framework. Then it's basically like this sample: https://stackoverflow.com/a/53842376/5947043 (the question is about .NET Core console apps but it will work just as well in .NET 4) – ADyson Jun 29 '22 at 09:51

1 Answers1

1

If you do not use a Inversion of control container or dependency injection framework up to now, you can implement the singleton like this:

public class SingletonServiceBusClient
{
  private static readonly SingletonServiceBusClient _instance
    = new SingletonServiceBusClient();
  private ServiceBusClient _client;

  // Private constructor to block instantiation outside of this class
  private SingletonServiceBusClient() { }

  public static SingletonServiceBusClient Instance { get => _instance; }

  public ServiceBusClient Client 
  { 
    get 
    {
      if (_client == null) 
        throw new ApplicationException("Please initialize the client first.");
      return _client; 
    }
  }

  public void Initialize(string connStr)
  {
    _client = new ServiceBusClient(connStr);
  }
}

At startup, you initialize the client like this:

SingletonServiceBusClient.Instance.Initialize("CONNSTR FROM CONFIG");

Afterwards, you can use this class like this:

var sender = SingletonServiceBusClient.Instance.Client.CreateSender("topic");
Markus
  • 20,838
  • 4
  • 31
  • 55