dependency-injectionunity-container.net-4.8

Inject instance from configuration file in net Framework


I am looking at a piece of code in a .NET Core application, and I am wondering if there is an equivalent and elegant way to achieve the result in .NET Framework 4.8

In core, you can "inject" (not sure about the correct terminology here) a class right from your configuration files like such.

Program.cs

builder.Services.Configure<FictionalRepositoryOptions>(
    builder.Configuration.GetSection(FictionalRepositoryOptions.Name)
);

FictionalRepositoryOptions.cs

public class FictionalRepositoryOptions
{
    /// <summary>Name of the section in the configuration to retrieve the</summary>
    public const string Name = "FictionalRepository";
 
    /// <summary>Secret for basic authentication</summary>
    public string Secret { get; init; } = String.Empty;
}

inside appsettings.json

"FictionalRepository": {
    "Secret": "secret value here"
},

That FictionalRepositoryOptions class can then be injected into the constructor and used through out the solution like below.

public Service(string baseUrl, FictionalRepositoryOptions options)
{
 var auth = new AuthenticationHeaderValue("Bearer", options.Secret);
}

Is there an elegant way to achieve this in netFramework with something like Unity Container?


Solution

  • Yes, you absolutely can. You can make use of the Microsoft.Extensions.Configuration package to load your configuration values (as described in detail here). After the configuration object is loaded, you can register it as single instance in Unity, after which, Unity will take care of the rest.

    using Microsoft.Extensions.Configuration;
    
    IConfigurationRoot config = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .AddEnvironmentVariables()
        .Build();
    
    FictionalRepositoryOptions options =
        config.GetSection("FictionalRepository")
            .Get<FictionalRepositoryOptions>();
    
    // TODO: Verify FictionalRepositoryOptions here (if required)
    
    // Register FictionalRepositoryOptions as singleton in the container.
    container.RegisterInstance(options);
    

    Note that there is no need to let your classes depend on IOptions<FictionalRepositoryOptions>. Classes can depend directly on FictionalRepositoryOptions.