2012-03-28 48 views
3

如何在運行時切換服務合同的實現?在WCF運行時切換服務合同實現

說我有:

[ServiceContract] 
public interface IService { 
    [OperationContract] 
    DoWork(); 
} 

public class ServiceA : IService { 
    public string DoWork() { 
     // .... 
    } 
} 

public class ServiceB : IService { 
    public string DoWork() { 
     // .... 
    } 
} 

我希望能夠切換正從說一個配置文件或值兩者之間的數據庫使用的實現。在WCF服務很熱的時候也可以這樣做嗎?

回答

3

您需要通過實現IServiceBehavior編寫servicebehavior,並使用實例提供程序初始化服務實例。下面初始化一個新的服務實例,您可以實現不同的邏輯:

public class XInstanceProviderServiceBehavior : Attribute, IServiceBehavior 
{   

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) 
    { 
     foreach (var item in serviceHostBase.ChannelDispatchers) 
     { 
      var dispatcher = item as ChannelDispatcher; 
      if (dispatcher != null) 
      { 
       dispatcher.Endpoints.ToList().ForEach(endpoint => 
       { 
        endpoint.DispatchRuntime.InstanceProvider = new XInstanceProvider(serviceDescription.ServiceType); 
       }); 
      } 
     } 
    } 

    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) 
    { 
    } 

    public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters) 
    { 
    } 
} 

,讓您的實例提供的類實現IInstanceProvider和getInstance方法返回相關的實例。

public XInstanceProvider :IInstanceProvider 
{ 
    ... 

    public object GetInstance(InstanceContext instanceContext, System.ServiceModel.Channels.Message message) 
    { 
     return new ServiceX(); 
    } 
} 

然後,您只需要添加servicebehaviour服務;像

[XInstanceProviderServiceBehavior()]  
    public class MyService : IMyService