autofac / Autofac.ServiceFabric

Autofac integration for Azure Service Fabric. Provides service factory implementations for Actors, Stateful Services and Stateless Services.
MIT License
26 stars 27 forks source link

Accessing CodePackageActivationContext #5

Closed Mardoxx closed 7 years ago

Mardoxx commented 7 years ago

For example, pulling configuration data from the CodePackage needed for service initialization

ServiceRuntime.RegisterServiceAsync("UserService",
    context =>
    {
        var configurationPackage = context.CodePackageActivationContext.GetConfigurationPackageObject("Config");
        var userStoreConnectionString = configurationPackage.Settings.Sections["UserStore"].Parameters["ConnectionString"].Value;

        var services = new ServiceCollection();
        services.AddDbContext<UserDbContext>(builder => builder.UseSqlServer(userStoreConnectionString ));
        services.AddScoped<IUserDbContext, UserDbContext>();
        services.AddScoped<IUserStore, UserStore>();

        var serviceProvider = services.BuildServiceProvider();
        return serviceProvider.GetRequiredService<UserService>();
    }).GetAwaiter().GetResult();

Is there a way to achieve this currently? Or do I have to think of a different way of storing configuration values? -- Is there a recommended method for retrieving service configuration data?

Mardoxx commented 7 years ago

There's the GetActivationContext() method on the FabricRuntime class.

private static void Main()
{
    try
    {
        var container = new ContainerBuilder();

        var services = new ServiceCollection();

        var activationContext = FabricRuntime.GetActivationContext();
        var configurationPackage = activationContext.GetConfigurationPackageObject("Config");
        var userStoreConnectionString = configurationPackage.Settings.Sections["UserStore"].Parameters["ConnectionString"].Value;

        services.AddDbContext<UserDbContext>(builder => 
                builder.UseSqlServer(userStoreConnectionString ));
        services.AddScoped<IUserDbContext, UserDbContext>();
        services.AddScoped<IUserStore, UserStore>();

        container.Populate(services);
        container.RegisterServiceFabricSupport();
        container.RegisterStatelessService<UserService>("UserService");

        using (container.Build())
        {
            ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(IdentityService).Name);
            Thread.Sleep(Timeout.Infinite);
        }
    }
    catch (Exception e)
    {
        ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString());
        throw;
    }
}

Something like this works perfectly! (For the interim until I make everything use AutoFac!)