Dependency injection in Akka.NET with state constructor options

Having something like a string parameter in the constructor makes dependency injection very dirty. Think:

public class CurrencyActor
{
    public CurrencyActor(string currency, IRepository repository)
    {
...

There were other questions (like this one ) for solving this particular problem with dependency injection. Often this is solved by redesigning and refactoring.

However, what if it actually makes sense to have several versions of the object, each of which is responsible for different data (for example, CurrencyActor for each currency)? This is pretty normal when using an acting model such as Akka.NET, but it makes sense even outside of this domain.

What is the best way to create these multiple instances using dependency injection while passing in the initial state they need?

+4
source share
1 answer

The presence of a dependency in a constructor is not random, it is very common. There is nothing wrong.

You can create a default static requisition method on CurrencyActor that takes your dependencies:

public static Props CreateProps(string currency, Irepository repo)
    {
        return Props.Create(() => new CurrrncyActor(currency, repo));
    }

Then create as many as you want:

var usCurrency = system.ActorOf(CurrencyActor.CreateProps("US", someRepo), "US");
var swedishCurrency = system.ActorOf(CurrencyActor.CreateProps("SEK", someRepo), "SEK");

[Update]

Regarding the use of DI containers with Akka, this has been indicated as not. 2 of 7 best mistakes people make when using akka.net

https://petabridge.com/blog/top-7-akkadotnet-stumbling-blocks/

, , DI.

. , , Autofac -

[ 2]

, - , , :

public class MatchesSupervisor : ReceiveActor
{
    List<IActorRef> _matches = new List<IActorRef>();
    public void MatchesSupervisor()
    {
        Receive<SomeCommandToStartANewMatch>(msg =>
        {
            // store the currently active matches somewhere, maybe on a FullTime message they would get removed?
            _matches.Add(Context.ActorOf(MatchActor.Create(msg.SomeMatchId)));
        }
    }
}

DI, MatchActor - , IRepository, MatchesSupervisor, , MatchActor, .

, , - , - .

( ipad, , , , , MatchActor, , , )

, !

+6

All Articles