.NET Services collection life time

132 Views Asked by At

is it possible to register some services later when the application up and running ?

I stuck into a scenario like this

I have WPF or MAUI application that use signalR for realtime communication, the problem is the application requirement doesn't want to force users to login to connect to the signalR hub, they can do it later.

And this is where the problem happen, if you register signalR when you boot up the app it will lack all the information about that user needed to connect to the hub because many scenarios users don't want to login first but they can do that when they want to

This question is not about SignalR it's about the life time of registering services to ServiceCollection.

1

There are 1 best solutions below

0
On

You would register the Service in MauiProgram.cs. Later the service can beresolved by calling the following code from any Method:

IServiceInterface serviceInstanceName=Shell.Current.Handler.MauiContext.Services.GetRequiredService<IServiceInterface>();

Replace Shell with this keyword where shell is not available:

IServiceInterface serviceInstanceName=this.Handler.MauiContext.Services.GetRequiredService<IServiceInterface>();

Service can be resolved directly if it's not implementing any interface.