【发布时间】:2016-07-10 17:43:39
【问题描述】:
我正在尝试使用 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?
【问题讨论】:
标签: c# dependency-injection akka.net