I have some doubts on how to correct implement dependency injection. Here it is suggested to use IndirectActorProducer
but it is not explained the reason. Or I don’t understand it.
For example another linked documentation on Let It crash, here, doesn’t mention about using IndirectActorProducer
.
Can someone explain it better?
I’m afraid those linked resources are quite dated. The let-it-crash article dates back to June 2013, the reference docs is certainly the authority of the two but as you note is very sparse on details.
In general I’d recommend just doing constructor based injection (that is, making an actor take what it needs to its constructor, and manually providing that when spawning instances of the actor) and not use a DI-framework if you can avoid it. If you really need to, you should be aware that fewer users use Akka like that and you may be somewhat on your own.
…however, there was a PR for a spring boot sample, that seems to have gone on ice but mays still be useful for inspiration: https://github.com/akka/akka-samples/pull/45
The Play Framework docs seem to focus on creating a component for injection with Guice and then doing manual constructor injection: https://www.playframework.com/documentation/2.7.x/ScalaAkka#Creating-and-using-actors
Thanks for the info @johanandren .
My main doubt is how to handle complex dependencies.
Let’s say that an actor needs a service (a db connection, a third party service, …). Can I just pass these dependencies inside Props
?
From my understanding Props must be serializable and probably these services will not be serializable. Correct?
How should I supposed to get a dependency like this from an actor?
Reading the Akka doc I think that in this case I should use IndirectActorProducer
. Correct? Using IndirectActorProducer
I can create actors and pass any dependencies without using the Props.
Props only needs to be serializable for remote deployment, which I’d recommend against using. In fact we are not going to support remote deployment for Akka Typed.
Note that a third party service or db connection itself is likely (but not always) a mutable state, that must not be shared across threads, and so is better encapsulated as an actor, so what you would inject is an actor ref that allows you to talk to the database.
If the dependency injection only to make mocks a common pattern with actors is to put creation in protected factory methods on the actor that can be overridden in the tests.