DEV Community

loading...

DI Service Configuration with .NET Options Pattern

Cesar Codes
I experiment with code and talk about it.
・1 min read

😮!

We're getting so close to .NET 5 that I didn't even add CORE in the title!

Anyway, I just want to share an easy way to get configuration from different sources into your services with .NET Co.... Corr... I mean, with .NET.

Ok, so in this example, I have a vault service and I'm also getting configuration from appsettings.json.

First thing I do is, I can create a config object for my service like this:

public class MyServiceOptions
{
    public string MyVaultSecret { get; set; }
    public string MyConfigVar { get; set; }
}

The question is, how can I pass it via dependency injection so that on my Startup.cs, my service is like this:

services.AddScoped<IMyService, MyService>();

The solution is to register your options like this. Refer to the official Microsoft options docs for more info. As you can see, I am using a reference to IVaultService, which can be any service.

services.AddOptions<MyServiceOptions>()
 .Configure<IVaultService>((o, v) => 
 {
     o.MyVaultSecret = v.GetSecret("SecretKey");
     o.MyConfigVar = Configuration["ConfigKey"];
 });

Anyway, now I can use my config like this:

public class MyService : IMyService
{
    private readonly IOptions<MyServiceOptions> _options;

    public MyService(
        IOptions<MyServiceOptions> o
        )
    {
        _options = o.Value;

        Console.WriteLine(_options.MyVaultSecret);
        Console.WriteLine(_options.MyConfigVar);
    }
}

Happy Coding,
Cesar Codes

Discussion (0)