Service Fabric Stateful Service with Asp.net Core

2019-06-23 18:50发布

I use Asp.net core DI correctly in my Stateless service since is basically a normal WebApi application with controllers.

I can't figure out how to use Dependency Injection in Stateful Services. This is the default constructor for the Stateful service:

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

And is called in Program.cs by

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

I would like to use something like this in the Stateful service:

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

I already registered it in the Configuration section of the Stateful service, but if I try to use the code above I have the error:

StatefulService does not contain a constructor that takes 0 arguments

How to make it work?

1条回答
祖国的老花朵
2楼-- · 2019-06-23 19:37

The error is about the constructor of StatefulService, it requires at least a ServiceContext parameter. Your code only supplies the Storagehelper.

This would be the simplest way to make it work:

Service:

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

Program:

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

In 'program' you could also use the IOC container to get the Storage helper instance.

查看更多
登录 后发表回答