3

how to use the constructor parameters, whose values are stored in the appsettings.json ?

services.AddTransient<IService, Service>(x => new Service("arg1", "arg2"));

I use the IOptions interface to read my config values

services.Configure<MyOptions>(Configuration.GetSection(nameof(MyOptions)));

3 Answers 3

7

If using IOptions<T> then update Service constructor to explicitly depend on IOptions<MyOptions> so that it can be injected into the class.

public class Service: IService {    
    public Service(IOptions<MyOptions> options) {
        this.arg1 = options.Value.arg1;
        this.arg2 = options.Value.arg2;
    }
}

Configuration can be simplified to

services.Configure<MyOptions>(Configuration.GetSection(nameof(MyOptions)));
services.AddTransient<IService, Service>();

Assuming appsettings.json contains

{
   "MyOptions": {
       "arg1": value1,
       "arg2": value2
    }
}

If unable to change service class constructor then resolve option in object factory delegate

services.AddTransient<IService, Service>(serviceProvider => {
    var options = serviceProvider.GetService<IOptions<MyOptions>>();
    return new Service(options.Value.arg1, options.Value.arg2);
});

Reference Options pattern in ASP.NET Core

Sign up to request clarification or add additional context in comments.

2 Comments

IOptions<T> is unnecessary, since the OP utilized services.Configure. That means they can inject MyOptions directly now. There is benefit in injecting IOptionsSnapshot<T>, as that gets you reload functionality, but given that the OP is adding a transient service, anyways, even that is superfluous.
@ChrisPratt That makes sense. Thank you for pointing that out.
2

The parameter in the lambda for that overload of AddTransient you're using is actually an instance of IServiceProvider. That means you can simply do:

services.AddTransient<IService, Service>(p => {
    var options = p.GetRequiredService<MyOptions>();
    return new Service(options.arg1, options.arg2);
});

Comments

1

You can get the values from appsettings.json with the frameworks IConfiguration interface.

Lets say your json is

{
   "argSection": 
    {
       "arg1": 1,
       "arg2": 2
    }
}

Then read the values like this

services.AddTransient<IService, Service>(x => new Service(Configuration["argSection:arg1"], Configuration["argSection:arg2"]));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.