4

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?

Francesco Cristallo
  • 2,856
  • 5
  • 28
  • 57

1 Answers1

2

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.

LoekD
  • 11,402
  • 17
  • 27
  • 1
    If he had an injection for IStorageHelper how would he go about getting the service instance to use in place of newing up a StorageHelper? – jKlaus Mar 08 '17 at 18:47