2013-02-26 97 views
2

我想從我們的內部.net應用程序使用DL​​L。如何使用配置節處理程序導入具有App.config的.NET DLL?

該DLL有一個App.config文件,並具有一個指定配置處理程序的配置部分。

我無法讓我的PowerShell腳本加載此dll。

我已經將問題簡化成最簡單的形式。

這裏是PowerShel劇本我想:

[appdomain]::CurrentDomain.SetData("APP_CONFIG_FILE", "D:\CustomConfig\CustomConfig\CustomConfigTestHarness\bin\Debug\CustomConfigTestHarness.exe.config") 
Add-Type -Path 'D:\CustomConfig\CustomConfig\CustomConfigTestHarness\bin\Debug\CustomConfig.dll' 
$mainClass = New-Object CustomConfig.Main 
$mainClass.TestConfig() 

這是配置文件:

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <configSections> 
     <section name="PrimarySqlServers" type="CustomConfig.ServerConfiguration, CustomConfig" /> 
    </configSections> 
    <PrimarySqlServers> 
     <Server name="data source=SQL\SQL2005; Initial Catalog=master; Trusted_Connection=yes;"/> 
    </PrimarySqlServers> 
</configuration> 

這裏是DLL:

namespace CustomConfig 
{ 
    public class Main 
    { 
     public string TestEcho(string message) 
     { 
      return message; 
     } 

     public string TestConfig() 
     { 
      Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
      string sectionName = "PrimarySqlServers"; 
      ServerConfiguration serverConfiguration = configuration.GetSection(sectionName) as ServerConfiguration; 
      if (serverConfiguration == null || serverConfiguration.ServerList.Count == 0) 
      { 
       throw new ConfigurationErrorsException(string.Format(CultureInfo.InvariantCulture, "ERR_MISSING_OR_EMPTY_SECTION", sectionName)); 
      } 
      ServerConfigurationEntry entry = serverConfiguration.ServerList[0]; 
      { 
       return entry.Name; 
      } 
     } 
    } 
} 

的configClass.cs文件全文如下:

using System; 
using System.Configuration; 
using System.Diagnostics; 

namespace CustomConfig 
{ 
    /// <summary> 
    /// Contains individual configuration information about a site to be deployed 
    /// </summary> 
    public class ServerConfiguration : ConfigurationSection 
    { 
     /// <summary> 
     /// Get the collection of assembly items 
     /// </summary> 
     [ConfigurationProperty("", IsDefaultCollection = true)] 
     public ServerConfigurationCollection ServerList 
     { 
      get { return (ServerConfigurationCollection) base[""]; } 
     } 
    } 

    /// <summary> 
    /// ContextCollection - represents the collection of context nodes 
    /// </summary> 
    public class ServerConfigurationCollection : ConfigurationElementCollection 
    { 
     /// <summary> 
     /// Get the assembly item element with the given name 
     /// </summary> 
     /// <param name="name">The name of the item you want</param> 
     /// <returns>The item specified</returns> 
     public new ServerConfigurationEntry this[string name] 
     { 
      get 
      { 
       if (IndexOf(name) < 0) return null; 
       return (ServerConfigurationEntry) BaseGet(name); 
      } 
     } 

     /// <summary> 
     /// Get a assembly item element by index 
     /// </summary> 
     /// <param name="index">The index of the item to get</param> 
     /// <returns>The item specified</returns> 
     public ServerConfigurationEntry this[int index] 
     { 
      get { return (ServerConfigurationEntry) BaseGet(index); } 
     } 

     /// <summary> 
     /// Clear the collection of items 
     /// </summary> 
     public void Clear() 
     { 
      BaseClear(); 
     } 

     /// <summary> 
     /// Add a new item to the collection 
     /// </summary> 
     /// <param name="name">The name of the site to add</param> 
     public void AddItem(string name) 
     { 
      ServerConfigurationEntry newEntry = new ServerConfigurationEntry(); 
      newEntry.Name = name; 
      this.BaseAdd(newEntry, true); 
     } 


     /// <summary> 
     /// Get the index of a given assembly item 
     /// </summary> 
     /// <param name="name">The name of the item to get the index of</param> 
     /// <returns>The index of the given item, or -1 if not found</returns> 
     public int IndexOf(string name) 
     { 
      for (int index = 0; index < base.Count; index++) 
      { 
       if (string.Compare(this[index].Name, name, StringComparison.OrdinalIgnoreCase) == 0) 
        return index; 
      } 

      return -1; 
     } 

     /// <summary> 
     /// Get the type of collection. BasicMap in this case. 
     /// </summary> 
     public override ConfigurationElementCollectionType CollectionType 
     { 
      get { return ConfigurationElementCollectionType.BasicMap; } 
     } 

     /// <summary> 
     /// Factory up a new element 
     /// </summary> 
     /// <returns>A new element</returns> 
     protected override ConfigurationElement CreateNewElement() 
     { 
      return new ServerConfigurationEntry(); 
     } 

     /// <summary> 
     /// Get the unique key for a assembly item element 
     /// </summary> 
     /// <param name="element">The element to get the key for</param> 
     /// <returns>A unique identifier for the element</returns> 
     protected override object GetElementKey(ConfigurationElement element) 
     { 
      return ((ServerConfigurationEntry) element).Name; 
     } 

     /// <summary> 
     /// Get the XML element name for elements of this type 
     /// </summary> 
     protected override string ElementName 
     { 
      get { return "Server"; } 
     } 
    } 

    /// <summary> 
    /// ContextElement - represents a single context element in the config 
    /// </summary> 
    [DebuggerDisplay("{Name}")] 
    public class ServerConfigurationEntry : ConfigurationElement 
    { 
     private const string NAME = "name"; 

     /// <summary> 
     /// Get or set the server name or connection string 
     /// </summary> 
     [ConfigurationProperty(NAME, DefaultValue = "", IsRequired = true, IsKey = true)] 
     public string Name 
     { 
      [DebuggerStepThrough] 
      get { return (string) this[NAME]; } 
      [DebuggerStepThrough] 
      set { this[NAME] = value; } 
     } 
    } 
} 

該錯誤消息我收到的時候我嘗試運行它是:

Exception calling `"TestConfig" with "0" argument(s)`: 

"An error occurred creating the configuration section handler for PrimarySqlServers: 
Could not load file or assembly 'CustomConfig' or one of its dependencies. The system cannot find the file specified. 
(D:\CustomConfig\CustomConfig\CustomConfigTestHarness\bin\Debug\CustomConfigTestHarness.exe.config line 4)" 
    At C:\dll.ps1:15 char:1 
    + $mainClass.TestConfig() 
    + ~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo   : NotSpecified: (:) [], MethodInvocationException 
    + FullyQualifiedErrorId : ConfigurationErrorsException 
+0

據我所見,CustomConfig.ServerConfiguration沒有被定義在任何地方 – 2013-02-26 08:34:21

+0

TestEcho方法是否工作?如果沒有,你可能會檢查http://stackoverflow.com/questions/2094694/how-can-i-run-powershell-with-the-net-4-runtime – nickvane 2013-02-26 09:59:55

+0

謝謝你看我的問題。是的,TestEcho工作正常。 – 2013-03-03 22:25:34

回答

0

嗯,我認爲在你的自定義配置節您的程序集的名稱不正確。

根據您的文章,這應該是:

<section name="PrimarySqlServers" type="CustomConfig.ServerConfiguration, CustomConfigTestHarness.exe" /> 

第二個參數是包含您CustomConfig.ServerConfiguration類型定義的程序集或可執行文件的名稱。

+0

感謝David,我忘了添加configclass.cs文件,現在我已經包含了這個。 – 2013-03-03 22:40:55

2

您遇到的問題是程序集不在.net的程序集搜索路徑中。

您可以通過許多不同的方式解決該問題(包括將組件放入GAC等)。

這可能是足夠的有關組裝其餘的信息添加到您的部分鍵(版本,區域性,公鑰標記......是這樣的:

<section name="PrimarySqlServers" type="CustomConfig.ServerConfiguration, CustomConfig, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" /> 

另一種方式是寫事件處理程序:

$configdll = 'D:\CustomConfig\CustomConfig\CustomConfigTestHarness\bin\Debug\CustomConfig.dll' 

[System.AppDomain]::CurrentDomain.add_AssemblyResolve({ 
    param($source, $assembly) 
    # Detect that they're looking for YOUR assembly specifically 
    if($assembly.Name.Split(",")[0] -eq "CustomConfig") { 
     # And load it for them: your path will be difference 
     return [System.Reflection.Assembly]::LoadFile($configdll ) 
    } 
}) 

另一種方式是把DLL在應用程序的主目錄 但在這種情況下,這是您的Windows \ SYSTEM32 \ WindowsPowerShell \ V1.0 \ ...所以這可能不是。一個偉大的計劃

+1

有用的注意事項是非常謹慎地處理塊中的其他引用。使用'join-path'或'System.IO.Path。Combine'導致重入到AssemblyResolve處理程序中,該處理程序依次執行重新進入處理程序等的語句,最終導致StackOverflowException異常。 – Tedford 2016-03-08 17:08:40

+0

謝謝,我遇到了同樣的問題,並添加了其他信息(Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null) – user1408786 2017-04-28 10:15:32

相關問題