Home > Enterprise >  want to put the model in "builder.Services.Configure"
want to put the model in "builder.Services.Configure"

Time:04-04

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();

Test Code and project here.



"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:

Code here.

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"

Code here.

builder.Services.AddScoped<ITestUtils, TestUtils>();

Used in controller constructor :

Code here.

    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);
});

enter image description here

  • Related