.NET Core DI Console

From no name for this wiki
Jump to: navigation, search
using System;
using System.IO;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace ConfigAggregate
{
    class Program
    {
        static void Main(string[] args)
        {

            IConfigurationBuilder builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false)
                .AddJsonFile("uc1.json", optional: false);

            IConfiguration configuration = builder.Build();

            ConfigRoot thisConfig = GetConfigRoot(configuration);

            IServiceProvider serviceProvider = new ServiceCollection()
                .AddSingleton(thisConfig)
                .AddScoped<IDemoService, DemoService>()
                .BuildServiceProvider();

            IDemoService service = serviceProvider.GetService<IDemoService>();

        }

        static ConfigRoot GetConfigRoot(IConfiguration configuration)
        {
            ConfigRoot thisConfig = new ConfigRoot();
            

            string[] sectionList = { "common", "uc1" };
            foreach(string section in sectionList)
            {
                ConfigRoot sectionConfig = new ConfigRoot();
                configuration.Bind(section, sectionConfig);


                thisConfig.ConfigItems = thisConfig.ConfigItems.Union(sectionConfig.ConfigItems).ToList();
            }

            return thisConfig;
        }
    }

    public class ConfigItem
    {
        public string Name { get; set; }
    }

    public class ConfigRoot
    {
        public IList<ConfigItem> ConfigItems { get; set; } = new List<ConfigItem>();
    }
    public interface IDemoService
    {
    }
    public DemoService(ConfigRoot root)
    {

    }
}
{
  "common": {
    "configItems": [
      { "name": "Claude" }
    ]
  }
}
{
  "uc1": {
    "configItems": [
      { "name": "SomeName" }
    ]
  }
}