I am creating a SignalRProxyService for a strongly typed signalR client and I am using Microsoft.AspNetCore.SignalR.Cleint.SourceGenerator as shown here.

Can you please help me in creating a generic method that takes any provider(i.e. ClientHubs Interfaces) and register it. So, I don't have to define every time about a new ClientHub in different places.

Currently - I am writing in my razor.cs pages:

RazorPageCS_SomeMethod()
{
    var HubConnection = new HubConnectionBuilder()
         .WithUrl($"{_serviceLocator.Find(user)}/{userHub}")
         .Build();
    var subscription = HubConnection.ClientRegistration<IUserHubClient>(new UserHubClient());
}

For ClientRegistration I created this method but can not find any better way instead of checking type of T every time when I add a ClientHub:


 private IDisposable RegisterHubClient<T>(string HubName, T action, HubConnection hubConnection)
 {
         IDisposable? subscription = default;
         //I have to do this for letting the SourceGenerator generate the code for the Specific ClientHub
         if (typeof(T) == typeof(IUserHubClient))
         {
             subscription = hubConnection.ClientRegistration<IUserHubClient>(new UserHubClient());

         }
         if (typeof(T) == typeof(IAccountHubClient))
         {
             subscription = hubConnection.ClientRegistration<IAccountHubClient>(new AccountHubClient());
          }

// Wanted to do something like this below but without writing the above code 
// the SourceGenerator is not auto generating code which causes error 
// (not able to find the specific ClientHub in .g.cs file)
         
subscription = hubConnection.ClientRegistration(action);
         return subscription;

 }

StartSignalRConnection() method:

 public async Task StartSignalRConnection(string hubName, string serviceName)
 {
     //creating hub connection logic...

    // code of RegisterHubClient
         var providerType = ProviderTypes[hubName];
         var method = typeof(SignalRProxyService).GetMethod(nameof(RegisterHubClient), BindingFlags.NonPublic | BindingFlags.Instance);
         if (method is not null)
         {
             object providerClass = new object();
             if (providerType == typeof(IUserHubClient))
             {
                 providerClass = new UserHubClient();
             }
             if (providerType == typeof(IAccountHubClient))
             {
                 providerClass = new AccountHubClient();
             }
            
             var genericMethod = method?.MakeGenericMethod(providerType);
             subscription = (IDisposable)genericMethod?.Invoke(this, new object[] { hubName, providerClass, HubConnection });
         }

// Start the hub connection
     
 }
0

There are 0 best solutions below