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)

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.