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)));
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
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);
});
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"]));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.