【问题标题】:Service Fabric Actor Service Dependency Injection and Actor EventsService Fabric Actor 服务依赖注入和 Actor 事件
【发布时间】:2017-01-31 13:22:43
【问题描述】:

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

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

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

我想添加我自己的构造函数,它有一个额外的接口被传入。你如何编写actor服务的注册以添加依赖项?在默认的 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();

但是在显示“() => 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;
    }
}

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

委托 'Func' 不取 0 论据

额外问题:

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

【问题讨论】:

    标签: c# dependency-injection azure-service-fabric service-fabric-actor


    【解决方案1】:
    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 的构造函数,并向下传递到基本构造函数。

    奖励答案:

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

    【讨论】:

    • 我有一个在我的 web-API 上构建 Autofac 注册的 web-api。 Autofac 注册接口和实现。是否可以在共享项目上使用接口(参与者服务接口)并让 web-API 使用 autofac 来实现这些?我正在尝试这种方式,因为这就是事件映射的设置方式。
    猜你喜欢
    • 2016-08-29
    • 2016-03-11
    • 2018-01-11
    • 1970-01-01
    • 2017-09-02
    • 2015-09-06
    • 2017-07-14
    • 2018-08-27
    • 2017-07-19
    相关资源
    最近更新 更多