using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Json; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using System; namespace CoreConsoleApp1 { class Program { static void Main(string[] args) { //DI容器测试 var provider1 = new ServiceCollection() .AddOptions() .AddTransient<IPerson, Person>() .AddTransient<IDog, Dog>() .AddTransient<IFly, Fly>() .BuildServiceProvider(); var dog1 = provider1.GetService<IDog>(); Console.WriteLine(provider1.GetService<IDog>().Name); Console.WriteLine(provider1.GetHashCode()); var provider2 = new ServiceCollection() .AddOptions() .AddTransient<IPerson, Person>() .AddTransient<IDog, Dog>() .BuildServiceProvider(); var dog2 = provider2.GetService<IDog>(); Console.WriteLine(provider2.GetHashCode()); //配置文件读取测试 IConfiguration config = new ConfigurationBuilder() .SetBasePath(AppContext.BaseDirectory) .Add(new JsonConfigurationSource { Path = "appsettings.json", Optional = false, ReloadOnChange = true }).Build(); ConfigHelper.config = config; var user = ConfigHelper.GetConfig<Usernfo>("User"); string url = ConfigHelper.GetValue("Url"); Console.WriteLine($"网址:{url}"); Console.WriteLine($"用户名:{user.Name},电话:{string.Join("|",user.Phones)}"); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Text; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Json; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; namespace CoreConsoleApp1 { public class ConfigHelper { public static IConfiguration config; public static string GetValue(string key) { return config.GetSection(key).Value; } public static T GetConfig<T>(string key) where T : class, new() { var data = new ServiceCollection() .AddOptions() .Configure<T>(config.GetSection(key)) .BuildServiceProvider() .GetService<IOptions<T>>() .Value; return data; } } }
using System; using System.Collections.Generic; using System.Text; namespace CoreConsoleApp1 { public interface IPerson { string Name { get; set; } } public class Person : IPerson { public string Name { get; set; } } public interface IDog { string Name { get; set; } } public class Dog : IDog { private IFly _fly; public Dog() { } public Dog(IFly fly) { _fly = fly; } public Dog(string name) { this.Name = name; } public string Name { get; set; } = "huahua"; } public interface IFly { string Fiy(); } public class Fly : IFly { public string Fiy() { return "fly...."; } } }
using System; using System.Collections.Generic; using System.Text; namespace CoreConsoleApp1 { public class Usernfo { public string Name { get; set; } public string[] Phones { get; set; } } }
appsettings.json { "Url": "http://www.test.com", "User": { "Name": "zhangsan", "Phones": [ "138002233", "12866525", "185226365" ] } }