Benutzer:MovGP0/Akka.NET/DI

aus Wikipedia, der freien Enzyklopädie
Zur Navigation springen Zur Suche springen
   MovGP0        Über mich        Hilfen        Artikel        Weblinks        Literatur        Zitate        Notizen        Programmierung        MSCert        Physik      


Akka.NET Dependency Injection

[Bearbeiten | Quelltext bearbeiten]
DI NuGet Packages Overview
Package Description
Akka.DI.Core Shared base classes for DI support
Akka.DI.Unity
Akka.DI.Ninject
Akka.DI.StructureMap
Akka.DI.AutoFac
Akka.DI.CastleWindsor
var someContainer = ... ;

// Create the actor system
var system = ActorSystem.Create("MySystem");

// Create the dependency resolver for the actor system
IDependencyResolver resolver = new XyzDependencyResolver(someContainer, system);

// Create the Props using the DI extension on your ActorSystem instance
var worker1Ref = system.ActorOf(system.DI().Props<TypedWorker>(), "Worker1");
var worker2Ref = system.ActorOf(system.DI().Props<TypedWorker>(), "Worker2");

Create Child Actor

[Bearbeiten | Quelltext bearbeiten]
// For example in the PreStart...
protected override void PreStart()
{
    var actorProps = Context.DI().Props<MyActor>()
        .WithRouter(/* options here */);

    var myActorRef = Context.ActorOf(actorProps, "myChildActor");
}

Actor Producer Extension

[Bearbeiten | Quelltext bearbeiten]
public sealed class MyDependencyResolver : IDependencyResolver
{
    IContainer Container { get; }
    ActorSystem System { get; }

    // Thread-Save Map 
    ConcurrentDictionary<string, Type> TypeCache { get; } 
        = new ConcurrentDictionary<string, Type>(StringComparer.InvariantCultureIgnoreCase);

    public WindsorDependencyResolver(IContainer myContainer, ActorSystem system)
    {
        if (system == null) throw new ArgumentNullException(nameof(system));
        if (myContainer == null) throw new ArgumentNullException(nameof(myContainer));

        Container = myContainer;
        System = system;

        System.AddDependencyResolver(this);
    }

    public Type GetType(string actorName)
    {
        return TypeCache.GetOrAdd(actorName, key => key.GetTypeValue());
    }

    public Func<ActorBase> CreateActorFactory(Type actorType)
    {
        return () => (ActorBase)Container.Resolve(actorType);
    }

    public Props Create<TActor>() where TActor : ActorBase
    {
        return System.GetExtension<DIExt>().Props(typeof(TActor));
    }

    // remove instances from DI container
    // or internal hashtable with references
    public void Release(ActorBase actor)
    {
        Container.Release(actor);
    }
}