简体   繁体   中英

Scoped dependency injection in Akka.Net

As we know Akka.Net already have some DI features so for example to create child actor we can write:

system.ActorOf(system.DI().Props<TypedWorker>(), "Worker1");

However Akka.Net solution is limited. My question is how would you approach scoped dependencies in Akka? There is already such proposal but no work have been done yet.

Lets say we have bunch of actors called Car and each car have quite complex hierarchy of child actors. Every Car have some data class called CarDetails but in whole hierarchy of child actors some of them would like to have access to CarDetails as well. Question is how to have CarDetails as a scoped dependency linked to Car so car childs can request this dependency in construtors?

What approach for such problem are you using in current Akka.Net implementation?

This is the problem, which you won't be able to solve using existing Dependency Injection frameworks - for a simple reason, that DI containers has been created mostly for services where the context-sensitive information doesn't exists (as it's simply not scalable to do so in dynamic environment with thousands-to-millions of different contexts working at any given time).

Given that CarDetails is immutable and readonly : you can simply send it as a constructor parameter to child actors.

If CarDetails is immutable but not readonly (ie it can be updated by parent): you can start from constructor param, then extend the behavior of the children to handle something like CarDetailsUpdated message, send by the updating actor, to replace the old state with a new one.

Finally if CarDetails is mutable : simply cut the parts that are actually required by every child into immutable messages/constructor params, and perform updates as above.

This is part of a principle known as don't communicate by sharing, share by communicating . It simply means to not try to share the mutable state between actors (since this will violate thread safety and require locks, that actors aim to solve), instead copy or provide immutable snapshot of a piece of the state and send it to every actor. This is an essential part of actor model programming.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM