【问题标题】:Service Fabric Stateful Service with Asp.net Core Dependency Injection使用 Asp.net 核心依赖注入的 Service Fabric 有状态服务
【发布时间】:2017-04-18 20:20:21
【问题描述】:

我在无状态服务中正确使用了 Asp.net 核心 DI,因为它基本上是一个带有控制器的普通 WebApi 应用程序。

我不知道如何在有状态服务中使用依赖注入。 这是有状态服务的默认构造函数:

 public MyService(StatefulServiceContext context): base(context)
        {            
        }

并且在 Program.cs 中被调用

ServiceRuntime.RegisterServiceAsync("MyStatefulType",context => new MyService(context)).GetAwaiter().GetResult();

我想在有状态服务中使用这样的东西:

  private readonly IHelpers _storageHelpers;
        public MyService(IHelpers storageHelpers)
        {
            _storageHelpers = storageHelpers;
        }

我已经在有状态服务的配置部分注册了它,但是如果我尝试使用上面的代码,我会遇到错误:

StatefulService 不包含采用 0 个参数的构造函数

如何让它发挥作用?

【问题讨论】:

    标签: asp.net-core asp.net-core-mvc azure-service-fabric service-fabric-stateful


    【解决方案1】:

    错误是关于StatefulService的构造函数,它至少需要一个ServiceContext参数。您的代码仅提供 Storagehelper。

    这是最简单的方法:

    服务

    private readonly IHelpers _storageHelpers;
    public MyService(StatefulServiceContext context, IHelpers storageHelpers) 
                : base(context)
    {
                _storageHelpers = storageHelpers;
    }
    

    计划

    ServiceRuntime.RegisterServiceAsync("MyStatefulType",context => new MyService(context, new StorageHelper())).GetAwaiter().GetResult();
    

    在“程序”中,您还可以使用 IOC 容器来获取存储助手实例。

    【讨论】:

    • 如果他对 IStorageHelper 进行了注入,他将如何使用服务实例来代替新的 StorageHelper?
    猜你喜欢
    • 1970-01-01
    • 2016-08-29
    • 2016-11-07
    • 2017-01-31
    • 1970-01-01
    • 2017-09-19
    • 2018-01-03
    • 1970-01-01
    • 2020-01-17
    相关资源
    最近更新 更多