akka.net

Akka.Hosting - Dependancy Injection in Actor parameter


How to inject parameters to Actors using Akka.Hosting? i.e. public ExampleActor(Service1 service){ _service = service; .... }

Service1 is a Service added to IServiceCollection during startup.


Solution

  • You can use Akka.DependencyInjection with Akka.Hosting via the following syntax:

    // arrange
    using var host = await StartHost(collection =>
    {
        collection.AddAkka("MyActorSys", (builder, sp) =>
        {
            builder.WithActors((system, registry, resolver) =>
            {
                var singletonActor = system.ActorOf(resolver.Props<SingletonActor>(), "singleton");
                registry.TryRegister<SingletonActor>(singletonActor);
            });
        });
    });
    
    // act
    var singletonInstance = host.Services.GetRequiredService<IMySingletonInterface>();
    var singletonActor = host.Services.GetRequiredService<ActorRegistry>().Get<SingletonActor>();
    var singletonFromActor =
        await singletonActor.Ask<IMySingletonInterface>(SingletonActor.GetSingleton.Instance, TimeSpan.FromSeconds(3));
    
    // assert
    singletonFromActor.Should().Be(singletonInstance);
    

    The WithActors line has an overload which exposes the DependencyResolver - that uses the IServiceProvider under the hood and you can use DependencyResolver.Props<TActor>(non-DI'd arguments...) to instantiate an actor that resolves dependencies through its constructor.