Is it possible to check if an actor exists in ActorSystem?
I just don't want to pass IActorRef reference to every actors constructor and would like to have something like GetOrCreate method to instantiate the required actor. So it could be like a singleton actor which I would use throughout the actor system.
You can check existence of any actor using ActorSelection to ask it to identify itself:
var selection = Context.ActorSelection(actorPath);
/// if there's no actor, this operation can timeout
var reply = await selection.Ask<ActorIdentity>(new Identify(null), timeout);
While this works everywhere, even across network boundaries, you cannot "just" create an actor from anywhere. In order to be created actor needs a parent - either an actor system or another actor.
Get or create logic can be done quite simply from inside of an actor:
IActorRef GetOrCreate(string childName)
{
var child = Context.Child(childName);
if (Equals(child, ActorRefs.Nobody))
child = Context.ActorOf(Props.Create(() => new ChildActor()), childName);
return child;
}
If you need to make it work in distributed environment, this functionality is covered by Akka.Cluster.Sharding plugin.