如何在Ninject中设置依赖注入?

时间:2016-07-10 17:43:39

标签: c# dependency-injection akka.net

我正在尝试使用Akka .NET设置依赖注入。在关于这个主题的Pluralsight课程之后,我提出了以下改编:

        var container = new StandardKernel();
        container.Bind<ITimeService>().To<LocalTimeService>();
        container.Bind<TimeLordActor>().ToSelf();

        using (var actorSystem = ActorSystem.Create("MyActorSystem"))
        {
            var resolver = new NinjectDependencyResolver(container, actorSystem);

            var actor = actorSystem.ActorOf(Props.Create<TimeLordActor>(),
                "TimeLordActor");
            actor.Tell("Give me the time!");

            Console.WriteLine("Press ENTER to exit...");
            Console.ReadLine();
        }

TimeLordActor的构造函数需要一个ITimeService类型的参数。

但是,运行时出现以下错误:

[ERROR][7/10/2016 5:39:42 PM][Thread 0012][akka://MyActorSystem/user/TimeLordActor] Error while creating actor instance of type AkkaNetDiExperimental.TimeLordActor with 0 args: () Cause: [akka://MyActorSystem/user/TimeLordActor#1586418697]: Akka.Actor.ActorInitializationException: Exception during creation ---> System.TypeLoadException: Error while creating actor instance of type AkkaNetDiExperimental.TimeLordActor with 0 args: () ---> System.MissingMethodException: Constructor on type 'AkkaNetDiExperimental.TimeLordActor' not found. at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark) at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) at System.Activator.CreateInstance(Type type, Object[] args) at Akka.Actor.Props.ActivatorProducer.Produce() at Akka.Actor.Props.NewActor() --- End of inner exception stack trace --- at Akka.Actor.Props.NewActor() at Akka.Actor.ActorCell.CreateNewActorInstance() at Akka.Actor.ActorCell.<>c__DisplayClass118_0.<NewActor>b__0() at Akka.Actor.ActorCell.UseThreadContext(Action action) at Akka.Actor.ActorCell.NewActor() at Akka.Actor.ActorCell.Create(Exception failure) --- End of inner exception stack trace --- at Akka.Actor.ActorCell.Create(Exception failure) at Akka.Actor.ActorCell.SysMsgInvokeAll(EarliestFirstSystemMessageList messages, Int32 currentState)

Akka .NET Dependency Injection上的官方文档建议您在直接创建actor时在ActorSystem实例上使用DI()扩展方法:

// 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");

但是,我甚至无法在actor系统上找到这种扩展方法。

有人可以解释如何使用actor系统本身的依赖注入来创建一个简单的actor?

1 个答案:

答案 0 :(得分:0)

我想出来了。您必须使用文档建议的DI()扩展方法。这是在Akka.DI.Core名称空间。

using Akka.DI.Core;

然后记得更新actor创建以反映文档使用的方法:

var actor = actorSystem.ActorOf(actorSystem.DI().Props<TimeLordActor>(),
                "TimeLordActor");