DEV Community 👩‍💻👨‍💻

Cesar Codes
Cesar Codes

Posted on

DI Service Configuration with .NET Options Pattern

😮!

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

Top comments (0)

16 Libraries You Should Know as a React Developer

Being a modern React developer is not about knowing just React itself. To stay competitive, it is highly recommended to explore the whole ecosystem. This article contains some of the most useful React component libraries to speed up your developer workflow.