akkadotnet / Akka.Hosting

Akka.Hosting - standardized Akka.NET hosting without any HOCON configuration. Ties into Microsoft.Extensions.Configuration, Logging, Hosting, and DependencyInjection.
Apache License 2.0
58 stars 16 forks source link

Chain of WithActors uses same service collection #482

Closed object closed 4 months ago

object commented 4 months ago

Version Information Akka.NET version 1.5.27 Which Akka.NET Modules? Akka.Hosting, Akka.Management

I am not sure this one is a bug, perhaps it was an intention to use the same service resolver while building Akka actors, but in some scenarios it becomes hard to bootstrap the system. Here's ours:

Is this intended that if I chain WithActors multiple times, then its respecitve instances of resolver will use the same copy of service collection, if though there may be new services registered in a call to WithActors? If so, then what is the recommended way to work around this problem?

object commented 4 months ago

I discussed this issue on Discord with @Arkatufus, closing this one.

Arkatufus commented 4 months ago

For future documentation:

Modifying the ServiceCollection inside the AddAkka() lambda function is not supported due to how Microsoft.Extensions.Hosting pipeline is being called. By the time the lambda function is invoked, the ServiceCollection is already built and the resulting ServiceProvider is passed into the lambda function.

The solution is to decouple the service and actor creation. Services were to be set-up outside the AddAkka() call, If a service requires a reference to an IActorRef, then it would inject IRequiredActor<T> in their constructor arguments and then to use IRequiredActor<T>.GetAsync() to retrieve the actor instance inside the service.