在WCF中在运行时切换服务契约实现

时间:2012-03-28 07:07:37

标签: c# .net wcf

我如何在运行时切换服务合同的实现?

说我有:

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

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

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

我希望能够在两者之间切换正在使用的实现,例如配置文件或数据库中的值。在WCF服务很热的时候也可以这样做吗?

1 个答案:

答案 0 :(得分: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