jamheadart
jamheadart

Reputation: 5313

How do I setup a service to receive some options in ASP.NET Core?

I'm just getting my head round setting up my own services to inject from Startup.cs in an ASP.NET Core 3.1+ project.

So far I created an interface and a class:

public interface IMyClass
{
    public string SomeString { get; set; }
}

public class MyClass : IMyClass
{
    public string SomeString { get; set; }
}

I added the service in startup using:

services.AddScoped<Services.IMyClass, Services.MyClass>();

Which works fine, except I want this class to have various strings it can return based on the current configuration and I have no idea how to pass those variables from appsettings.json to populate SomeString so I can then get it from in a controller.

I was trying this:

services.AddScoped<Services.IMyClass, Services.MyClass>(
    Configuration.GetValue<string>("SomeAppSettingKey");

To pull a string from appsettings, but don't know how to populate a constructor in the class with the string. Do I need to add some sort of options class as a property in MyClass ?


There's lots of hints on how I can be adding some of these config settings but I'm just missing some info e.g.

        services.AddTransient<IMyClass, MyClass>();
        services.Configure<MyClass>(Configuration);

Makes syntactical sense to me but I'm still not sure how to populate the string in MyClass by passing the Configuration here.

Upvotes: 0

Views: 1129

Answers (1)

Nkosi
Nkosi

Reputation: 247068

Create a model to store the setting extracted from configuration

public class MyClassOptions {
    public string SomeAppSettingKey { get; set; }
}

(Note the matching names)

Configure it at Startup

services.Configure<MyClassOptions>(Configuration);

(This assumes the key is in the root of the settings file)

Update the target class to inject the options configured

public class MyClass : IMyClass {

    public MyClass (IOptions<MyClassOptions> options) {
        SomeString = options.Value.SomeAppSettingKey;
    }

    public string SomeString { get; set; }
}

Reference Options pattern in ASP.NET Core

Upvotes: 3

Related Questions