代码之家  ›  专栏  ›  技术社区  ›  SteinTech

如何配置自定义配置对象

c#
  •  1
  • SteinTech  · 技术社区  · 7 年前

    我正在尝试注册一个自定义配置对象,但不知道如何配置它。我尝试使用ServiceCollection。配置<&燃气轮机;(),但是

    无法从“”系统转换。配置“配置部分”至

    namespace LC.Assets.Core.Utility.Config
    {
        public interface ILCToolsConfig
        {
            int SiteId { get; set; }
            IShopsConfig Shops { get; set; }
            ISiteConfig Site { get; set; }
        }
    
        public class LCToolsConfig : ILCToolsConfig
        {
            public int SiteId { get; set; }
            public IShopsConfig Shops { get; set; } = new ShopsConfig();
            public ISiteConfig Site { get; set; } = new SiteConfig();
        }
    }
    

    商店配置。反恐精英 :

    namespace LC.Assets.Core.Utility.Config
    {
        public interface IShopsConfig
        {
            int Id { get; set; }
        }
    
        public class ShopsConfig : IShopsConfig
        {
            public int Id { get; set; }
        }
    }
    

    :

    namespace LC.Assets.Core.Utility.Config
    {
        public interface ISiteConfig
        {
            int Id { get; set; }
        }
    
        public class SiteConfig : ISiteConfig
        {
            public int Id { get; set; }
        }
    }
    

    配置代码

    services.AddSingleton<Configuration>();
    services.AddOptions();
    
    Configuration c = services.BuildServiceProvider().GetRequiredService<Configuration>();
    
    services.Configure<LCToolsConfig>(c.GetSection("LCTools"));
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   SteinTech    7 年前

    解决方案 :

    代码,配置 :

    IConfiguration c = provider.GetRequiredService<IConfiguration>();
    var cnf = new LCToolsConfig();
    c.Bind("LCTools", cnf);
    
    services.AddOptions();
    services.AddSingleton(cnf);
    

    public StoreController(LCToolsConfig config) { }
    

    谢谢

        2
  •  -1
  •   rory.ap    7 年前

    换衣服 services.Configure<LCToolsConfig>(c.GetSection("LCTools")); services.Configure<LCToolsConfig>(() => c.GetSection("LCTools"));

    services.Configure<T>() 他正在找一个 System.Action 作为一个参数,您将从 c.GetSection() 哪一个是 System.Configuration.ConfigurationSection 系统行动