Reputation: 86
This is my class :
public class entityClass
{
public string id { get; set; }
public string os { get; set; }
}
and this is my appsetings.json
:
{
"key1": {
"id": "4",
"os": "XP"
}
}
Please help me to fix this:
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;
}
}
It's very convenient at ASP.NET Core but it doesn't happen on the console...
I want to get the right answer in exactly the same way...
This is exactly the style of the code I wrote in ASP.NET Core MVC
Upvotes: 0
Views: 403
Reputation: 19106
Your provided code has no error where you comment it but 3 other:
Here is how to fix them:
IServiceProvider
and use that to create an instance of ClassController
. To do so you also have to register that class to the ServiceCollection
.YMethod
from the ClassController
instance to get an instance of entityClass
.service1.AddTransient<ClassController>();
var provider = service1.BuildServiceProvider();
var test = provider.GetRequiredService<ClassController>().YMethod();
Here is the final result
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
service1.AddTransient<ClassController>();
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;
}
}
Upvotes: 0