问题
I find it very unintuitive that the ServiceRuntime.RegisterServiceAsync returns before the service is actually registered and the factory Func that is passed as a parameter completes.
Think about the scenario where you need to resolve the same ServiceName you're registering. You can only get the ServiceName from the ServiceContext you get in the serviceFactory Func. You'd think you could resolve within the serviceFactory Func once you get the context. But then you enter a "deadlock" where the resolve call would get stuck forever since it waits for the service you're registering to finish.
This is why I'd expect for the RegisterServiceAsync to complete only after serviceFactory Func is completed too.
回答1:
It returns before the method runs because the ServiceRuntime.RegisterServiceAsync() is a factory registration, it is not a constructor building the service.
Signature:
public Task RegisterStatefulServiceFactoryAsync(string serviceTypeName, IStatefulServiceFactory factory, TimeSpan timeout, CancellationToken cancellationToken)
The concept here is to tell the Runtime that whenever the runtime need to start an instance of the serviceTypeName it should call the factory Func<System.Fabric.StatefulServiceContext,Microsoft.ServiceFabric.Services.Runtime.StatefulServiceBase>. This factory is the function responsible to setup the dependencies required for that service, and if you need to do dependency injection, you would do at this point.
The runtime need first to have the dependencies registered before it start building the services. Very similar to what you do on ASPNET when you add the dependency registrations and once all dependencies are registered, you call Start().
At a later point, the runtime will be ready and will receive the instructions from SF to start the actual service instance from a specific service type, at this point these factories will be called and the context build. If you need to know the serviceTypeName before you actually receive a call for it, it would be the chicken and the egg dilemma.
It works this way, because you can have multiple replicas running on same host, so each instance will have it's own context. And you could also have multiple serviceTypes on same host.
来源:https://stackoverflow.com/questions/53759837/why-does-serviceruntime-registerserviceasync-return-before-the-servicefactory-fu