如何像ASP.NET Core一样通过依赖注入将json数据绑定到类上

问题描述 投票:0回答:1

这是我的课:

public class entityClass
{
    public string id { get; set; }
    public string os { get; set; }
}

这是我的

appsetings.json

{
  "key1": {
    "id": "4",
    "os": "XP"
  }
}

请帮我解决这个问题:

class Program
{
    static void Main(string[] args)
    {
        IConfiguration configur = new ConfigurationBuilder()  //using Microsoft Configuration
                .SetBasePath(@"C:\ConsoleApp26\").AddJsonFile("appsetting.json").Build();

        ServiceCollection service1 = new ServiceCollection(); //using Microsoft DependencyInjection
        service1.Configure<entityClass>(configur.GetSection("key1")); //Error

        var test = new ClassController();
        Console.WriteLine(test.id + "==>" + test.os);
    }
}

class ClassController
{
    private readonly IOptions<entityClass> _entity;            //using Microsoft.Extensions.Options;

    public ClassController(IOptions<entityClass> entity)
    {
        _entity = entity;
    }

    public entityClass YMethod()
    {
        var view = _entity.Value;
        return view;
    }
}

在 ASP.NET Core 上非常方便,但在控制台上却不会发生...

我想以完全相同的方式得到正确的答案...

这正是我在 ASP.NET Core MVC 中编写的代码风格

enter image description here

c# asp.net-core dependency-injection configuration ioptionsmonitor
1个回答
0
投票

您提供的代码您评论时没有错误,但还有其他 3 个错误:

以下是修复它们的方法:

  1. 您必须构建一个
    IServiceProvider
    并使用它来创建
    ClassController
  2. 的实例
  3. YMethod
    实例调用
    ClassController
    以获取
    entityClass
    的实例。
var provider = service1.BuildServiceProvider();
var test = provider.GetRequiredService<ClassController>().YMethod();

这是最终结果

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace ConsoleApp1;

public class entityClass
{
    public string id { get; set; }
    public string os { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        IConfiguration configur = new ConfigurationBuilder()  //using Microsoft Configuration
                .SetBasePath(@"C:\ConsoleApp26\")
                .AddJsonFile("appsetting.json")
                .Build();

        ServiceCollection service1 = new ServiceCollection(); //using Microsoft DependencyInjection
        service1.Configure<entityClass>(configur.GetSection("key1")); //Error

        var provider = service1.BuildServiceProvider();
        var test = provider.GetRequiredService<ClassController>().YMethod();
        
        Console.WriteLine(test.id + "==>" + test.os);
    }
}

class ClassController
{
    private readonly IOptions<entityClass> _entity;            //using Microsoft.Extensions.Options;

    public ClassController(IOptions<entityClass> entity)
    {
        _entity = entity;
    }

    public entityClass YMethod()
    {
        var view = _entity.Value;
        return view;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.