Search code examples
c#autofacazure-service-fabric

Injecting Servics Fabric ServiceContext into Config implementations using DI


I'm trying to read my configuration from SF configuration using the 'ConfigurationPackage' that is available from any SF service context. My class looks like this:

internal class ServiceFabricDbConfiguration : IDbConnectionConfig
{
    private ConfigurationPackage _configurationPackage;

    public ServiceFabricDbConfiguration(ServiceContext context)
    {
        _configurationPackage = context.CodePackageActivationContext.GetConfigurationPackageObject("Config");
    }

    public string UserName =>
        _configurationPackage.Settings.Sections["Db_Configuration"]
            .Parameters[
                "Username"]
            .Value;
}

I'm using autofac as my DI container, and can register the above class by explicitly capturing a reference to the ServiceContext when i register it with the SF runtime:

ServiceRuntime.RegisterServiceAsync("ApiType",
                        context =>
                        {
                            Bootstrapper.SetContext(context);
                            return new Api(context);
                        })
                    .GetAwaiter()
                    .GetResult();

Is there a way that i can register the ServiceContext with the bootstrapper, ideally within the bootstrapper class?

I'm currently experimenting with using Autofac.ServiceFabric to register my actors/services, but that hides the ServiceContext so makes the above harder to achieve again (though does make it far easier to maintain clean autofac module definitions)


Solution

  • There's the static method GetActivationContext() in FabricRuntime. You could perhaps use this to inject the activation context.

    There's also, in development, Autofac.ServiceFabric https://github.com/autofac/Autofac.ServiceFabric which may be of use to you. There's a blog post about it here https://alexmg.com/introducing-the-autofac-integration-for-service-fabric/ which also contains links to sample code! It's in pre-release (beta) at the moment but I have been using it without issue for the past few months.