如何在 Ninject 中设置依赖注入
本文关键字:设置 依赖 注入 Ninject | 更新日期: 2023-09-27 17:56:26
我正在尝试使用 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 依赖注入的官方文档建议,在直接创建 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");
但是,我甚至无法在演员系统上找到这种扩展方法。
有人可以解释如何使用参与者系统本身的依赖注入来创建一个简单的参与者吗?
通了。您必须按照文档的建议使用DI()
扩展方法。这位于 Akka.DI.Core
命名空间中。
using Akka.DI.Core;
然后记得更新Actor创建以反映文档使用的方法:
var actor = actorSystem.ActorOf(actorSystem.DI().Props<TimeLordActor>(),
"TimeLordActor");