c# - .NET 8 console dependency injection pass data from JSON to class not working - Stack Overflow

I have the following code and if I run it with line 36 comment removed, I get the data from the .json f

I have the following code and if I run it with line 36 comment removed, I get the data from the .json file into the variable CollarSurveyPickupSettings.

If I then run the cspvm line at row 37 (CollarSurveyPickupVM), it sends the 3 DbContext data loaded, the Options loaded, but no data in CollarSurveyPickupM collarSurveyModel, AcquireCommandLineM acquireCommandLineModel, or PeggingSettingsM peggingModel.

I am not sure what I am doing wrong? Any help would be appreciated.

I have also added a git repository

program.cs:

using CommandLine;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using RHOKSAutomationConsole.CollarSurvey;
using RHOKSAutomationConsole.EFACQ;
using RHOKSAutomationConsole.EFRHOKS2020;
using RHOKSAutomationConsole.EFRHOKS2024;
using RHOKSAutomationConsole.Pegging;
using RHOKSAutomationConsole.Settings;

namespace RHOKSAutomationConsole;

public class Options
{
    [Option("DataSource", Required = true, Default = "TEST", HelpText = "Data Source as TEST or PROD")]
    public string? DataSource { get; set; }
}

internal class Program
{
    //private static AppM? ApplicationData;
    //private static AcquireCommandLineM? ACQCommandLineData;
    //private static CollarSurveyPickupM? CollarSurveyPickupSettings;
    //private static PeggingSettingsM? PeggingSettings;

    static void Main(string[] args)
    {
        Parser.Default.ParseArguments<Options>(args)
             .WithParsed<Options>(options =>
             {
                 using IHost host = CreateHostBuilder(options).Build();
                 //IConfiguration config = host.Services.GetRequiredService<IConfiguration>();
                 //CollarSurveyPickupSettings = config.GetSection("CollarSurveyPickups").Get<CollarSurveyPickupM>() ?? new CollarSurveyPickupM();
                 var cspvm = host.Services.GetRequiredService<CollarSurveyPickupVM>();
             });
    }

    #region HostBuilder
    public static IHostBuilder CreateHostBuilder(Options optionsq) =>
        Host.CreateDefaultBuilder()
        .ConfigureAppConfiguration((context, config) =>
        {
            config
            .AddJsonFile(string.Concat(Directory.GetCurrentDirectory(), "\\Settings\\appsettings.json"), optional: false, reloadOnChange: true)
            .AddJsonFile(string.Concat(Directory.GetCurrentDirectory(), "\\Settings\\SerilogSettings.json"), optional: false, reloadOnChange: true)
            .AddConfiguration(context.Configuration)
            .AddUserSecrets<Program>()
            .AddEnvironmentVariables();
        })
        .ConfigureServices((hostContext, services) =>
        {
            IConfiguration config = hostContext.Configuration;

            //services.Configure<AppSettingsM>(options => config.GetSection("ApplicationSettings").Bind(options));
            services.Configure<SerilogSettingsM>(options => config.GetSection("Serilog").Bind(options));
            services.Configure<AcquireCommandLineM>(options => config.GetSection("SECRET_ACQ_Credentials").Bind(options));
            services.Configure<CollarSurveyPickupM>(options => config.GetSection("CollarSurveyPickups").Bind(options));
            services.Configure<PeggingSettingsM>(options => config.GetSection("OreDefPegging").Bind(options));

            services.AddDbContext<RHOKS_2020Context>(
                options => options.UseSqlServer(
                    $"Data Source=" +
                    $"{config.GetSection("SqlConfigurations:VM.SQL:SQLServer").Get<string>()}" +
                    $"\\" +
                    $"{config.GetSection("SqlConfigurations:VM.SQL:SQLInstance").Get<string>()};" +
                    $"Initial Catalog={config.GetSection("SqlConfigurations:VM.SQL:SQLDatabaseRHOKS2020").Get<string>()}" +
                    $";Trusted_Connection=True;TrustServerCertificate=True;", x => x.UseNetTopologySuite()).EnableSensitiveDataLogging(true), ServiceLifetime.Transient);

            services.AddDbContext<RHOKS_2024Context>(
                options => options.UseSqlServer(
                    $"Data Source=" +
                    $"{config.GetSection("SqlConfigurations:VM.SQL:SQLServer").Get<string>()}" +
                    $"\\" +
                    $"{config.GetSection("SqlConfigurations:VM.SQL:SQLInstance").Get<string>()};" +
                    $"Initial Catalog={config.GetSection("SqlConfigurations:VM.SQL:SQLDatabaseRHOKS2024").Get<string>()}" +
                    $";Trusted_Connection=True;TrustServerCertificate=True;", x => x.UseNetTopologySuite()).EnableSensitiveDataLogging(true), ServiceLifetime.Transient);

            services.AddDbContext<ACQContext>(
                options => options.UseSqlServer(
                    $"Data Source=" +
                    $"{config.GetSection("SqlConfigurations:ACQ.SQL:SQLServer").Get<string>()}" +
                    $"\\" +
                    $"{config.GetSection("SqlConfigurations:ACQ.SQL:SQLInstance").Get<string>()};" +
                    $"Initial Catalog={config.GetSection("SqlConfigurations:ACQ.SQL:SQLDatabaseACQ").Get<string>()}" +
                    $";Trusted_Connection=True;TrustServerCertificate=True;", x => x.UseNetTopologySuite()).EnableSensitiveDataLogging(true), ServiceLifetime.Transient);

            services.AddSingleton<Options>(optionsq);

            services.AddSingleton<AppM>();

            services.AddSingleton<AcquireCommandLineM>();
            services.AddSingleton<PeggingSettingsM>();

            services.AddSingleton<CollarSurveyPickupM>();
            services.AddSingleton<CollarSurveyPickupVM>();
    }

    //.UseSerilog((context, services, configuration) => configuration
    //.ReadFrom.Configuration(context.Configuration)
    //.ReadFrom.Services(services)
    );
    #endregion HostBuilder
}

CollarSurveyPickupVM:

using CommunityToolkit.Mvvm.ComponentModel;
using CsvHelper;
using CsvHelper.Configuration;
using Microsoft.IdentityModel.Tokens;
using RHOKSAutomationConsole.EFACQ;
using RHOKSAutomationConsole.EFRHOKS2020;
using RHOKSAutomationConsole.EFRHOKS2024;
using RHOKSAutomationConsole.Pegging;
using RHOKSAutomationConsole.Settings;
using System.Globalization;

namespace RHOKSAutomationConsole.CollarSurvey;

public partial class CollarSurveyPickupVM : ObservableObject
{
    [ObservableProperty] CollarSurveyPickupM? m_CollarSurveyPickupSettings;
    [ObservableProperty] AcquireCommandLineM? m_AcquireCommandLineModel;
    [ObservableProperty] Options m_OptionsData;
    [ObservableProperty] RHOKS_2024Context m_Rhoks2024Context;
    [ObservableProperty] RHOKS_2020Context m_Rhoks2020Context;
    [ObservableProperty] ACQContext m_AcquireContext;

    public CollarSurveyPickupVM(
        RHOKS_2024Context rhoks2024context,
        RHOKS_2020Context rhoks2020context,
        ACQContext acquirecontext,
        Options options,
        CollarSurveyPickupM? collarSurveyModel,
        AcquireCommandLineM acquireCommandLineModel,
        PeggingSettingsM peggingModel
        )
    {
        Rhoks2024Context = rhoks2024context ?? throw new ArgumentNullException(nameof(rhoks2024context));
        Rhoks2020Context = rhoks2020context ?? throw new ArgumentNullException(nameof(rhoks2020context));
        AcquireContext = acquirecontext ?? throw new ArgumentNullException(nameof(acquirecontext));
        OptionsData = options ?? throw new ArgumentNullException(nameof(options));
        PeggingModel = peggingModel ?? throw new ArgumentNullException(nameof(peggingModel));
        AcquireCommandLineModel = acquireCommandLineModel ?? throw new ArgumentNullException(nameof(acquireCommandLineModel));
        CollarSurveyPickupSettings = collarSurveyModel ?? throw new ArgumentNullException(nameof(collarSurveyModel));
    }

    public PeggingSettingsM PeggingModel { get; }
}

I have the following code and if I run it with line 36 comment removed, I get the data from the .json file into the variable CollarSurveyPickupSettings.

If I then run the cspvm line at row 37 (CollarSurveyPickupVM), it sends the 3 DbContext data loaded, the Options loaded, but no data in CollarSurveyPickupM collarSurveyModel, AcquireCommandLineM acquireCommandLineModel, or PeggingSettingsM peggingModel.

I am not sure what I am doing wrong? Any help would be appreciated.

I have also added a git repository https://github/JemQDev/RHOKSAutomationConsole

program.cs:

using CommandLine;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using RHOKSAutomationConsole.CollarSurvey;
using RHOKSAutomationConsole.EFACQ;
using RHOKSAutomationConsole.EFRHOKS2020;
using RHOKSAutomationConsole.EFRHOKS2024;
using RHOKSAutomationConsole.Pegging;
using RHOKSAutomationConsole.Settings;

namespace RHOKSAutomationConsole;

public class Options
{
    [Option("DataSource", Required = true, Default = "TEST", HelpText = "Data Source as TEST or PROD")]
    public string? DataSource { get; set; }
}

internal class Program
{
    //private static AppM? ApplicationData;
    //private static AcquireCommandLineM? ACQCommandLineData;
    //private static CollarSurveyPickupM? CollarSurveyPickupSettings;
    //private static PeggingSettingsM? PeggingSettings;

    static void Main(string[] args)
    {
        Parser.Default.ParseArguments<Options>(args)
             .WithParsed<Options>(options =>
             {
                 using IHost host = CreateHostBuilder(options).Build();
                 //IConfiguration config = host.Services.GetRequiredService<IConfiguration>();
                 //CollarSurveyPickupSettings = config.GetSection("CollarSurveyPickups").Get<CollarSurveyPickupM>() ?? new CollarSurveyPickupM();
                 var cspvm = host.Services.GetRequiredService<CollarSurveyPickupVM>();
             });
    }

    #region HostBuilder
    public static IHostBuilder CreateHostBuilder(Options optionsq) =>
        Host.CreateDefaultBuilder()
        .ConfigureAppConfiguration((context, config) =>
        {
            config
            .AddJsonFile(string.Concat(Directory.GetCurrentDirectory(), "\\Settings\\appsettings.json"), optional: false, reloadOnChange: true)
            .AddJsonFile(string.Concat(Directory.GetCurrentDirectory(), "\\Settings\\SerilogSettings.json"), optional: false, reloadOnChange: true)
            .AddConfiguration(context.Configuration)
            .AddUserSecrets<Program>()
            .AddEnvironmentVariables();
        })
        .ConfigureServices((hostContext, services) =>
        {
            IConfiguration config = hostContext.Configuration;

            //services.Configure<AppSettingsM>(options => config.GetSection("ApplicationSettings").Bind(options));
            services.Configure<SerilogSettingsM>(options => config.GetSection("Serilog").Bind(options));
            services.Configure<AcquireCommandLineM>(options => config.GetSection("SECRET_ACQ_Credentials").Bind(options));
            services.Configure<CollarSurveyPickupM>(options => config.GetSection("CollarSurveyPickups").Bind(options));
            services.Configure<PeggingSettingsM>(options => config.GetSection("OreDefPegging").Bind(options));

            services.AddDbContext<RHOKS_2020Context>(
                options => options.UseSqlServer(
                    $"Data Source=" +
                    $"{config.GetSection("SqlConfigurations:VM.SQL:SQLServer").Get<string>()}" +
                    $"\\" +
                    $"{config.GetSection("SqlConfigurations:VM.SQL:SQLInstance").Get<string>()};" +
                    $"Initial Catalog={config.GetSection("SqlConfigurations:VM.SQL:SQLDatabaseRHOKS2020").Get<string>()}" +
                    $";Trusted_Connection=True;TrustServerCertificate=True;", x => x.UseNetTopologySuite()).EnableSensitiveDataLogging(true), ServiceLifetime.Transient);

            services.AddDbContext<RHOKS_2024Context>(
                options => options.UseSqlServer(
                    $"Data Source=" +
                    $"{config.GetSection("SqlConfigurations:VM.SQL:SQLServer").Get<string>()}" +
                    $"\\" +
                    $"{config.GetSection("SqlConfigurations:VM.SQL:SQLInstance").Get<string>()};" +
                    $"Initial Catalog={config.GetSection("SqlConfigurations:VM.SQL:SQLDatabaseRHOKS2024").Get<string>()}" +
                    $";Trusted_Connection=True;TrustServerCertificate=True;", x => x.UseNetTopologySuite()).EnableSensitiveDataLogging(true), ServiceLifetime.Transient);

            services.AddDbContext<ACQContext>(
                options => options.UseSqlServer(
                    $"Data Source=" +
                    $"{config.GetSection("SqlConfigurations:ACQ.SQL:SQLServer").Get<string>()}" +
                    $"\\" +
                    $"{config.GetSection("SqlConfigurations:ACQ.SQL:SQLInstance").Get<string>()};" +
                    $"Initial Catalog={config.GetSection("SqlConfigurations:ACQ.SQL:SQLDatabaseACQ").Get<string>()}" +
                    $";Trusted_Connection=True;TrustServerCertificate=True;", x => x.UseNetTopologySuite()).EnableSensitiveDataLogging(true), ServiceLifetime.Transient);

            services.AddSingleton<Options>(optionsq);

            services.AddSingleton<AppM>();

            services.AddSingleton<AcquireCommandLineM>();
            services.AddSingleton<PeggingSettingsM>();

            services.AddSingleton<CollarSurveyPickupM>();
            services.AddSingleton<CollarSurveyPickupVM>();
    }

    //.UseSerilog((context, services, configuration) => configuration
    //.ReadFrom.Configuration(context.Configuration)
    //.ReadFrom.Services(services)
    );
    #endregion HostBuilder
}

CollarSurveyPickupVM:

using CommunityToolkit.Mvvm.ComponentModel;
using CsvHelper;
using CsvHelper.Configuration;
using Microsoft.IdentityModel.Tokens;
using RHOKSAutomationConsole.EFACQ;
using RHOKSAutomationConsole.EFRHOKS2020;
using RHOKSAutomationConsole.EFRHOKS2024;
using RHOKSAutomationConsole.Pegging;
using RHOKSAutomationConsole.Settings;
using System.Globalization;

namespace RHOKSAutomationConsole.CollarSurvey;

public partial class CollarSurveyPickupVM : ObservableObject
{
    [ObservableProperty] CollarSurveyPickupM? m_CollarSurveyPickupSettings;
    [ObservableProperty] AcquireCommandLineM? m_AcquireCommandLineModel;
    [ObservableProperty] Options m_OptionsData;
    [ObservableProperty] RHOKS_2024Context m_Rhoks2024Context;
    [ObservableProperty] RHOKS_2020Context m_Rhoks2020Context;
    [ObservableProperty] ACQContext m_AcquireContext;

    public CollarSurveyPickupVM(
        RHOKS_2024Context rhoks2024context,
        RHOKS_2020Context rhoks2020context,
        ACQContext acquirecontext,
        Options options,
        CollarSurveyPickupM? collarSurveyModel,
        AcquireCommandLineM acquireCommandLineModel,
        PeggingSettingsM peggingModel
        )
    {
        Rhoks2024Context = rhoks2024context ?? throw new ArgumentNullException(nameof(rhoks2024context));
        Rhoks2020Context = rhoks2020context ?? throw new ArgumentNullException(nameof(rhoks2020context));
        AcquireContext = acquirecontext ?? throw new ArgumentNullException(nameof(acquirecontext));
        OptionsData = options ?? throw new ArgumentNullException(nameof(options));
        PeggingModel = peggingModel ?? throw new ArgumentNullException(nameof(peggingModel));
        AcquireCommandLineModel = acquireCommandLineModel ?? throw new ArgumentNullException(nameof(acquireCommandLineModel));
        CollarSurveyPickupSettings = collarSurveyModel ?? throw new ArgumentNullException(nameof(collarSurveyModel));
    }

    public PeggingSettingsM PeggingModel { get; }
}
Share Improve this question edited Nov 26, 2024 at 3:23 Zhi Lv 21.7k1 gold badge27 silver badges37 bronze badges asked Nov 21, 2024 at 5:33 QuentinQuentin 455 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

You are registering your option models:

services.Configure<CollarSurveyPickupM>(options => config.GetSection("CollarSurveyPickups").Bind(options));

and registering them as normal injectable services as well (not sure why as singletons (?), read more about lifetimes here)

services.AddSingleton<CollarSurveyPickupM>();

So when you inject them as normal services, you'll get them resolved as normal services:

public CollarSurveyPickupVM(CollarSurveyPickupM collarSurveyModel)
{
    CollarSurveyPickupSettings = collarSurveyModel ?? throw new ArgumentNullException(nameof(collarSurveyModel));
}

To inject them as options bind against IConfiguration you need to inject them as such. So, as IOptions<T>:

public CollarSurveyPickupVM(IOptions<CollarSurveyPickupM> collarSurveyModelOptions)
{
    CollarSurveyPickupSettings = collarSurveyModelOptions?.Value ?? throw new ArgumentNullException(nameof(collarSurveyModelOptions));
}

You can also simplify your option registration calls by passing the configuration section to the Configure() call, omitting the action delegate. It will have the same result; options for CollarSurveyPickupM type will be registered to bind against the "CollarSurveyPickups" section:

services.Configure<CollarSurveyPickupM>(config.GetSection("CollarSurveyPickups"));

Final note

Your code suffers from mixing up of service layers and models. You should separate those. Use services for business logic and models for data transportation. I'm not an expert in MVVM architecture, but I'm sure enough that models should not act as both and have DI slapped on top of that.

Finally, it is worth a read: Dependency injection in ASP.NET Core

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742312202a4420119.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信