这是我的课:
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 中编写的代码风格
以下是修复它们的方法:
IServiceProvider
并使用它来创建 ClassController
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;
}
}