Reputation: 433
I would like to use remoting in a .net core stateful service. I have a custom class which needs to be added as a singleton. Is this possible?
First I tried to register the custom class in Startup.cs's ConfigureServices() method but then I realized this method will be never called, since I used return this.CreateServiceRemotingReplicaListeners();
to generate my replica listeners in the CreateServiceReplicaListeners() method, and removed the Kestrel configuration (which would make this method to be called).
Is there a way to make the Startup.cs's ConfigureServices() method to be called, or add the singleton service at another place while keeping the remoting configuration?
The CreateServiceReplicaListeners() method in the MyStefulService.cs class looks like the following:
protected override IEnumerable<ServiceReplicaListener>
CreateServiceReplicaListeners()
{
return this.CreateServiceRemotingReplicaListeners();
}
The ConfigureServices method in the Startup.cs looks like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IMyHandler>(x => new MyHandler());
}
Upvotes: 1
Views: 144
Reputation: 433
Finally i found a solution to my problem: I used Autofac to make sure the class I register is the same instance wherever it is used. I extended the Program.cs with the Autofac container, so this way I didn't need the Startup.cs class at all:
I defined static variable of my custom class and an Autofac container, then in Main() method I added the implementation:
public static IContainer AutofacContainer;
private static IMyHandler _handler;
private static void Main()
{
try
{
if (_autofacContainer == null)
{
var builder = new ContainerBuilder();
builder.RegisterType<MyHandler>()
.As<IMyHandler>()
.SingleInstance();
_autofacContainer = builder.Build();
_handler = autofacContainer.Resolve<IMyHandler>();
}
//[...] normal service registration continues here
}
catch (Exception e)
{
ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString());
throw;
}
}
Since the container is static and public, all the other classes in the project can access it and get the singleton instance. Configuration, environment variables, etc. can also be configured from here, similarly to the Startup.cs.
Upvotes: 1