我想做的是将两个演员(妈妈演员和爸爸演员)传递给儿童演员。由于使用演员参考而不是演员是最佳实践,因此我使用 IActorRef 为木乃伊演员和爸爸演员通过 DI 注入命名参数。但我收到“mummyActor 不是唯一的”错误。知道如何解决吗?
using System;
using System.Threading.Tasks;
using Akka.Actor;
using Akka.DI.AutoFac;
using Akka.DI.Core;
using Autofac;
using Autofac.Core;
namespace Akka.DI.AutoFac.ExampleConsole {
public class DaddyActor : ReceiveActor {
public DaddyActor() {
Receive<DoneEatingMessage>(m => {
Console.WriteLine("Kid finished eating. So what? ~ Dad");
});
}
}
public class MummyActor : ReceiveActor {
public MummyActor() {
Receive<DoneEatingMessage>(m => {
Console.WriteLine("Kid finished eating. Time to clean up! ~Mummy");
});
}
}
public class KidActor : ReceiveActor {
private IService _service;
private IActorRef _mummyActor;
private IActorRef _daddyActor;
public KidActor(IService service, IActorRef mummyActor, IActorRef daddyActor) {
this._service = service;
this._mummyActor = mummyActor;
this._daddyActor = daddyActor;
Receive<EatMessage>(m=>{
var food = service.GetFood();
Console.WriteLine("Kid eat this food {0}", food);
_mummyActor.Tell(new DoneEatingMessage());
});
}
}
public class EatMessage{ }
public class DoneEatingMessage { }
public interface IService {
string GetFood();
}
public class FoodService : IService {
public string GetFood() {
return "banana";
}
}
class Program {
static ActorSystem _actorSystem;
static void Main(string[] args) {
var builder = new Autofac.ContainerBuilder();
builder.RegisterType<FoodService>().As<IService>();
builder.RegisterType<MummyActor>().InstancePerDependency();
builder.RegisterType<DaddyActor>().InstancePerDependency();
builder.Register(c => _actorSystem.ActorOf(_actorSystem.DI().Props<DaddyActor>(), "daddyActor"))
.Named<IActorRef>("daddyActorRef")
.AsSelf();
builder.Register(c => _actorSystem.ActorOf(_actorSystem.DI().Props<MummyActor>(), "mummyActor"))
.Named<IActorRef>("mummyActorRef")
.AsSelf();
builder.RegisterType<KidActor>()
.WithParameter(
new ResolvedParameter(
(pi, ctx) => pi.ParameterType == typeof(MummyActor),
(pi, ctx) => ctx.ResolveNamed<IActorRef>("mummyActorRef")
)
)
.WithParameter(
new ResolvedParameter(
(pi, ctx) => pi.ParameterType == typeof(DaddyActor),
(pi, ctx) => ctx.ResolveNamed<IActorRef>("daddyActorRef")
)
)
.InstancePerDependency();
var container = builder.Build();
_actorSystem = ActorSystem.Create("ActorDISystem");
var propsResolver = new AutoFacDependencyResolver(container, _actorSystem);
var kidActorProps = _actorSystem.DI().Props<KidActor>();
var kidActor = _actorSystem.ActorOf(kidActorProps, "kidActor");
kidActor.Tell(new EatMessage());
Console.WriteLine("Holah");
Console.ReadLine();
}
}
}