2015-12-14 20 views
0

我正在使用wcf服務,其中服務在動態隨機端口上託管。服務契約和服務行爲程序集動態加載,並且所有類型都將被掃描以匹配服務名稱及其版本。 相同的服務可以在不同的版本上運行。爲了區分服務的版本,我們創建了一個自定義的ServiceIdentifierAttribute屬性。檢查是否有任何類在裝配中定義了定製屬性,其中自定義屬性和類都是動態裝載的

public class ServiceIdentifierAttribute : Attribute 
    { 
     private string _name; 
     public string Name 
     { 
      get { return _name; } 
      set { _name = value; } 
     } 

     private string _version; 
     public string Version 
     { 
      get { return _version; } 
      set { _version = value; } 
     } 
    } 

服務契約及其行爲類用SerivceIdentifierAttribute裝飾。

[ServiceContract(Name = "ABCServicesV0.0.0.0")] 
    [ServiceIdentifierAttribute(Name = "ABCServicesV0.0.0.0", Version = "V0.0.0.0")] 
    public interface IABCService 
    { 
    } 

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple, Name = "ABCServicesV0.0.0.0")] 
    public class ABCService : IABCService 
    {} 

服務契約,屬性在一個程序集中定義,而服務實現在另一個程序集中定義。我們有一個GenericSericeHost控制檯應用程序,通過加載這兩個程序集來動態託管服務。我們需要搜索所有類型並從程序集中獲取服務合同類型。

private static bool SeachForServiceContractAttribute(Type type, String serviceIdentifier) 
     { 
      if (type.IsDefined(typeof(ServiceContractAttribute), false)) 
      { 
       var attributeTypes = type.GetCustomAttributes(); 
       foreach (var attributeType in attributeTypes) 
       { 
        try 
        { 
         ServiceContractAttribute attribute = (ServiceContractAttribute)attributeType; 
         if (attribute != null && !string.IsNullOrEmpty(attribute.Name) && attribute.Name.Equals(serviceIdentifier)) 
          return true; 
        } 
        catch (Exception ex) 
        { 
         Console.Write(ex.Message); 
        } 
       } 
      } 
     return false; 
     } 

GenericServiceHost引用了ServiceContract程序集。運行時 ServiceContractAttribute attribute = (ServiceContractAttribute)attributeType; 正在拋出錯誤無效的轉換異常。由於ServiceContractAttribute的兩個版本在運行時被加載。一個是動態加載的,另一個是GenerciServiceHost引用。我們不能刪除服務引用,因爲它會導致ServiceContractAttribute未定義的複雜錯誤。

所有不同的服務實現將有不同的程序集,我們不想添加對來自genereicservicehost的所有程序集的引用,因爲當任何服務行爲發生更改時,它將導致重建genericservicehost。我們希望GenericServiceHost始終運行。

我們怎樣才能使這個由鑄從裝配裝型工作負載裝配型

ServiceContractAttribute attribute = (ServiceContractAttribute)attributeType; 

任何指針?

+0

爲什麼要加載兩次?一個屬性是一個基礎設施的東西,該組件應該簡單地引用。動態加載其他內容應該對該程序集沒有影響。 – Ralf

回答

1

您的架構有缺陷。看來你已經宣佈ServiceContractAttribute多次,然後是的,演員不會永遠工作,因爲每個聲明產生不同類型。

你必須分解ServiceContractAttribute到一個單獨的組件限定主機應用程序和服務組件之間的通用API,並在所有的服務共享。