cap7
cap7

Reputation: 522

Providing configurations to static classes in .Net Core

I'm curious regarding what approaches can be taken to solve the following problem.

I was using Properties.Settings.Default in a WPF app to store some configurations. It occurred to me that it should be possible to decouple the code from this variable. So I've come up with something like this to enable the DI of a configuration class:

public partial class App : Application
{
    private ServiceProvider _serviceProvider;

    protected override void OnStartup(StartupEventArgs e)
    {
        //configureSservices and buildServiceProvider
    }

    private void ConfigureServices(IServiceCollection services)
    {
        var configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .Build();
        
        services.AddSingleton<IConfiguration>(configuration);
        services.AddTransient<MainWindow>();
        services.AddTransient<IMainViewModel, MainViewModel>();
        services.AddTransient<IDataService, DataService>();
    }
}

Considering this code, if I want to use the Configuration in other classes I can do it like this:

public class MyClass
{
    private readonly IConfiguration _config;

    public MyClass(IConfiguration config)
    {
        _config = config;
        var mySetting = _config["MySetting"];
    }

    //or even like this...
    public void MyMethod()
    {
        var config = ServiceProvider.GetService<IConfiguration>();
        var mySetting = config["MySetting"];
        // ...
    }
}

My problem now is how to use this configurations in static classes, that are already using Properties.Settings.Default on too many places, since none of the previous is possible.

I guess that one possible approach would be to refactor all the static methods like this:

public static class MyStaticClass
{
    public static void MyMethod(IConfiguration config)
    {
        var mySetting = config["MySetting"];
    }
}

What would be shortcomings to this solutions? Would it be better to make them none static (despite the fact that they only provide utility methods)?

Thank you for reading!

Upvotes: 1

Views: 2238

Answers (2)

Shojaeddin
Shojaeddin

Reputation: 2073

You can make static method in that static class to get setting like below

    private static ApplicationSettings GetSiteSettings(IServiceCollection services)
{
    var provider = services.BuildServiceProvider();
    var siteSettingsOptions = provider.GetRequiredService<IOptionsSnapshot<ApplicationSettings>>();
    var siteSettings = siteSettingsOptions.Value;
    if (siteSettings == null) throw new ArgumentNullException(nameof(siteSettings));
    return siteSettings;
}

then call this method in that static class

Upvotes: 0

boylec1986
boylec1986

Reputation: 589

You cannot inject dependencies in to static classes because the scope/lifetime of static classes is independent of the main app thread.

By the time the processor hits the lines of code where DI is being registered in App those static classes have already fired up in memory.

Set some breakpoints on the register statements and the static class code and you'll see that static classes are initialized before your App.cs has even started.

The solution is to only use static classes for things that don't require configuration - utility type functions and things of that nature rather than functions that deal with the business logic of your application.

Ask yourself: Why are these static? Likely you won't have a great reason for that.

Upvotes: 5

Related Questions