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!
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!
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");