Search code examples
c#asp.net-corehealth-check

How to use a connectionStringFactory in AspNetCore.Diagnostics.HealthCheck.AddSqlServer()?


The AddSqlServer health check has a method signature that accepts a factory for a connection strings.

public static IHealthChecksBuilder AddSqlServer(
            this IHealthChecksBuilder builder,
            Func<IServiceProvider, string> connectionStringFactory, ...)

I'm not exactly sure how to implement this. I have a factory that returns connection strings but it requires some IOptions to be injected into it. Also, I don't understand how a factory which is being added as a service to the builder could be used at this same point where the health checks are being added. I don't think it can be done.

builder.Services.AddOptions() // some options added here
builder.Services.AddScoped<IConnectionStringFactory, ConnectionStringFactory>();
builder.Services.AddHealthChecks()
    .AddSqlServer(_ =>
    {
        factoryCalled = true; // how do I get my factory here?
        return "connectionstring";
    });

This leads me to ask how they intended this to be used? Am I expected to provide a new instance of my factory? If that's the case then this becomes less interesting as I would need to also manually create everything that needs injected into the factory.


Solution

  • I'm doing this from memory, but you should be able to call GetService in your delegate block there:

    builder.Services.AddHealthChecks()
        .AddSqlServer(_ =>
        {
            var factory = builder.Services.GetService<IConnectionStringFactory>();
            factoryCalled = true;
            return factory.Build();
        });