在构造函数中具有依赖关系并不麻烦,它非常常见。这没有什么问题。
你可以在 CurrencyActor 上创建一个默认的 props 静态方法来接收你的依赖:
public static Props CreateProps(string currency, Irepository repo)
{
return Props.Create(() => new CurrrncyActor(currency, repo));
}
然后根据需要创建任意数量:
var usCurrency = system.ActorOf(CurrencyActor.CreateProps("US", someRepo), "US");
var swedishCurrency = system.ActorOf(CurrencyActor.CreateProps("SEK", someRepo), "SEK");
[更新]
关于在 Akka 中使用 DI 容器,这被列为否。人们在使用 akka.net 时常犯的 7 个错误中的 2 个
https://petabridge.com/blog/top-7-akkadotnet-stumbling-blocks/
因此,参与者管理自己的依赖项而不是将工作委托给 DI 框架被认为是一种很好的做法。
所以基本上不要这样做。如果你必须,根据那篇文章,Autofac 是最好的选择
[更新 2]
如果您想动态创建同一 Actor 的新实例但更改一些初始状态,那么您可以有一个负责创建它们的主管:
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 使用时传递给它们创建的。
这也有点取决于状态来自哪里,以及启动新匹配的机制是什么 - 我只是假设其他一些 Actor 正在发送消息。
(我在 ipad 上打字,所以上面的代码实际上可能无法编译,但希望你明白,我还省略了 MatchActor 的实现,但它只是一个将一些值传递给其构造函数的 Actor )
希望这会有所帮助!