Service Fabric Actor 服务依赖项注入和 Actor 事件

Jus*_*eff 4 c# dependency-injection azure-service-fabric service-fabric-actor

当参与者服务启动时,我想自动订阅文档中描述的任何事件。手动订阅事件是有效的。但是,当实例化服务时,是否有一种方法可以自动订阅参与者服务,就像在 OnActivateAsync() 中一样?

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

使用 Microsoft.ServiceFabric.Actors.2.2.207 应该支持对 Actor 服务的依赖项注入。现在,在实现 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();
Run Code Online (Sandbox Code Playgroud)

但是,在显示“() => new 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

委托“Func”不接受 0 个参数

奖金问题:

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

Vac*_*cek 6

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();
Run Code Online (Sandbox Code Playgroud)

创建 Actor 实例的函数的签名是:

Func<ActorService, ActorId, ActorBase>
Run Code Online (Sandbox Code Playgroud)

ActorService该框架提供了和的实例ActorId,您可以将其传递给 Actor 的构造函数并通过基本构造函数向下传递。

奖金答案:

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