3

当演员服务启动时,我想自动订阅文档中描述的任何事件。手动订阅事件有效。但是,当服务被实例化时,是否有办法自动订阅参与者服务,例如在 OnActivateAsync() 中?

我试图做的是通过依赖注入来解决这个问题,即在 MyActor 类的实例化中,它传递一个接口, OnActivateAsync 调用该接口为客户端订阅事件。但是我遇到了依赖注入的问题。

使用 Microsoft.ServiceFabric.Actors.2.2.207 应该支持对参与者服务的依赖注入。现在,在实现 Microsoft.ServiceFabric.Actors.Runtime.Actor 时,会使用 ActorService 和 ActorId 参数创建一个默认构造函数。

我想添加我自己的构造函数,该构造函数传入了一个额外的接口。你如何编写演员服务的注册以添加依赖项?在默认 Program.cs Main 它提供了这个

IMyInjectedInterface myInjectedInterface = null;

// inject interface instance to the UserActor
ActorRuntime.RegisterActorAsync<MyActor>(
   (context, actorType) => new ActorService(context, actorType, () => new MyActor(myInjectedInterface))).GetAwaiter().GetResult();

但是在它说“()=>新MyActor(myInjectedInterface)”的那一行它告诉我一个错误

委托 'Func' 不接受 0 个参数

查看 Actor 类的构造函数,它具有以下内容

MyActor.Cs

internal class MyActor : Microsoft.ServiceFabric.Actors.Runtime.Actor, IMyActor
{
    private ActorService _actorService;
    private ActorId _actorId;
    private IMyInjectedInterface _myInjectedInterface;

    public SystemUserActor(IMyInjectedInterface myInjectedInterface, ActorService actorService = null, ActorId actorId = null) : base(actorService, actorId)
    {
        _actorService = actorService;
        _actorId = actorId;
        _myInjectedInterface = myInjectedInterface;
    }
}

1) 如何解决我在尝试解决 Actor 依赖项时收到的错误?

委托 'Func' 不接受 0 个参数

奖金问题:

当我的无状态服务(调用客户端)调用接口实例时,如何解析 IMyInjectedInterface 以注入到参与者服务中?

4

1 回答 1

4
IMyInjectedInterface myInjectedInterface = null;
//inject interface instance to the UserActor

ActorRuntime.RegisterActorAsync<MyActor>(
    (context, actorType) => new ActorService(context, actorType, 
        (service, id) => new MyActor(myInjectedInterface, service, id)))

    .GetAwaiter().GetResult();

创建你的actor实例的函数的签名是:

Func<ActorService, ActorId, ActorBase>

该框架提供了一个实例ActorServiceActorId您可以将其传递给 Actor 的构造函数,并通过基础构造函数向下传递。

奖励答案:

这里的用例与您所想的略有不同。这里的模式是一种通过接口解耦具体实现的通用模式——它不是客户端应用程序修改运行时行为的一种方式。所以调用客户端不提供依赖的具体实现(至少不通过构造函数注入)。依赖项是在编译时注入的。IoC 容器通常会这样做,或者您可以手动提供一个。

于 2016-09-22T22:53:04.047 回答