.net核心中XML配置文件中的自定义部分

时间:2018-06-07 13:38:54

标签: c# .net-core

我有一个问题,配置问题。

我正在.net core 2.0下运行一个带有自定义配置文件的应用程序:

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

  <configSections>
    <section name="mailingListSection" type="ConfigurationTool.AppServer.PersistenceLayer.Entities.MailingList, ConfigurationTool.AppServer.PersistenceLayer.Entities" />
  </configSections>

  <mailingListSection>
    <mails>
      <mail value="test1@test.com" />
     <mail value="test2@test.com" />
   </mails>
 </mailingListSection>

 <appSettings>
   <add key="Path" value="Value"/>
 </appSettings>

现在你看到我有一个自定义部分,我想从配置中获取,所以我创建了配置元素集合:

namespace ConfigurationTool.AppServer.PersistenceLayer.Entities
{
    public class MailingList : ConfigurationSection
    {
        [ConfigurationProperty("mails")]
        public MailElementCollection Mails
        {
            get => (MailElementCollection)base["mails"];
            set => base["mails"] = value;
        }
    }
    public class MailElement : ConfigurationElement
    {
        [ConfigurationProperty("value", IsRequired = true, IsKey = true)]
        public string Value => (string)base["value"];
    }

    [ConfigurationCollection(typeof(MailElement))]
    public class MailElementCollection : ConfigurationElementCollection
    {
        internal const string PropertyName = "mail";

        public override ConfigurationElementCollectionType CollectionType => ConfigurationElementCollectionType.BasicMapAlternate;

        protected override string ElementName => PropertyName;

        protected override bool IsElementName(string elementName)
        {
            return elementName.Equals(PropertyName, StringComparison.InvariantCultureIgnoreCase);
        }

        public override bool IsReadOnly()
        {
            return false;
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return new MailElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((MailElement)element).Value;
        }

        public new MailElement this[string value] => (MailElement)BaseGet(value);
    }
}

并尝试称之为:

var map = new ExeConfigurationFileMap { ExeConfigFilename = "persistenceLayer.config" };
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

var mailingList = config.GetSection("mailingListSection");

但我得到了

  

块引用   为mailingListSection创建配置节处理程序时发生错误:   无法加载文件或程序集   &#39; ConfigurationTool.AppServer.PersistenceLayer.Entities,Culture = neutral,PublicKeyToken = null&#39;。

我已经检查了我的主应用程序目录配置文件是否还有ConfigurationTool.AppServer.PersistenceLayer.dll,并且我有想法,可能出错?

另外的信息是主要应用程序指的是那个。

1 个答案:

答案 0 :(得分:0)

确保将ConfigurationTool.AppServer.PersistenceLayer.Entities设置为项目中的参考。然后单击引用列表中的引用,并在属性窗口中将Copy Local设置为true。