Benutzer:MovGP0/Akka.NET/DI

aus Wikipedia, der freien Enzyklopädie
< Benutzer:MovGP0‎ | Akka.NET
Dies ist die aktuelle Version dieser Seite, zuletzt bearbeitet am 3. Dezember 2015 um 19:51 Uhr durch imported>MovGP0(77247) (→‎Usage).
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)
   MovGP0        Über mich        Hilfen        Artikel        Weblinks        Literatur        Zitate        Notizen        Programmierung        MSCert        Physik      


Akka.NET Dependency Injection

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

Usage

Create Actor

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

// 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

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);
    }
}