Search code examples
dependency-injection.net-coreazure-service-fabric

Set up Dependency Injection on Service Fabric using default ASP.NET Core DI container


I would like to use ASP.NET Core's default DI container to setup DI for my Service Fabric project.

//This is what I've got so far, and it works great
ServiceRuntime.RegisterServiceAsync(
  "MyServiceType",
  context => new MyService(context, new MyMonitor()
).GetAwaiter().GetResult();

//This is how I use it
public MyService(StatefulServiceContext context, IMonitor myMonitor)
  : base(context)
{
  this._myMonitor = myMonitor;           
}

How would I set up DI, if MyMonitor class has a dependency on a ConfigProvider class, like this:

public MyMonitor(IConfigProvider configProvider)
{
  this._configProvider = configProvider;
}

Solution

  • I think this question will give you some light: Why does ServiceRuntime.RegisterServiceAsync return before the serviceFactory func completes?

    Technically, the ServiceRuntime.RegisterServiceAsync() is a dependency registration, it requires you to pass the serviceTypeName and the factory method responsible for creating the services Func<StatelessServiceContext, StatelessService> serviceFactory

    The factory method receives the context and returns a service (Stateful or stateless).

    For DI, you should register all dependencies in advance and call resolve services to create the constructor, something like:

    var provider = new ServiceCollection()
                .AddLogging()
                .AddSingleton<IFooService, FooService>()
                .AddSingleton<IMonitor, MyMonitor>()
                .BuildServiceProvider();
    
    ServiceRuntime.RegisterServiceAsync("MyServiceType",
        context => new MyService(context, provider.GetService<IMonitor>());
    }).GetAwaiter().GetResult();
    

    PS:

    • Never Register the context (StatelessServiceContext\StatefulServiceContext) in the DI, in a shared process approach, multiple partitions might be hosted on same process and will have multiple contexts.
    • This code snippet is not tested, I've used in the past, don't have access to validate if matches the same code, but is very close to the approach used, might need some tweaks.