When configuring the builder in "ASP.NET Core", I want to put the data model I created myself.
It is intended to be delivered to middleware or "Add Scoped" services.
I've tried the following code:
TestUtilsSettingModel temp = new TestUtilsSettingModel()
{
Test01 = 1000,
Test03 = "Input!!"
};
//error
builder.Services
.Configure<TestUtilsSettingModel>(temp);
//error
builder.Services
.Configure<TestUtilsSettingModel>(
new Action<TestUtilsSettingModel>(temp));
//https://stackoverflow.com/a/45324839/6725889
builder.Configuration["TestUtilsSetting:Test01"] = 1000.ToString();
"Configuration["TestUtilsSetting:Test01"]" works but
You have to put all the data yourself.
Can't you just pass the whole data model?
Here is the test code:
class to receive options:
public interface ITestUtils
{
}
public class TestUtils: ITestUtils
{
private readonly TestUtilsSettingModel _appSettings;
public TestUtils(IOptions<TestUtilsSettingModel> appSettings)
{
_appSettings = appSettings.Value;
}
}
Inject from "Program.cs" or "Startup.cs"
builder.Services.AddScoped<ITestUtils, TestUtils>();
Used in controller constructor :
public WeatherForecastController(
ILogger<WeatherForecastController> logger
, ITestUtils testMiddleware)
{
_logger = logger;
this._TestMiddleware = testMiddleware;
}
CodePudding user response:
I studied 'iservicecollection extension' to solve this problem.
I found a solution.
The following code is equivalent to
'builder.Configuration["TestUtilsSetting:Test01"] = 1000.ToString();'
builder.Services.Configure<TestUtilsSettingModel>(options =>
{
options.Test01 = 1000;
});
You still have to put each one in.
('options = temp' not work)
So do something like this:
Add the following method to 'TestUtilsSettingModel'.
public void ToCopy(TestUtilsSettingModel testUtilsSettingModel)
{
this.Test01 = testUtilsSettingModel.Test01;
this.Test02 = testUtilsSettingModel.Test02;
this.Test03 = testUtilsSettingModel.Test03;
}
In 'Program.cs', pass the model as follows.
builder.Services.Configure<TestUtilsSettingModel>(options =>
{
options.ToCopy(temp);
});