gpt4 book ai didi

c# - 在 WCF ServiceHost 中提供工厂而不是类型

转载 作者:太空宇宙 更新时间:2023-11-03 20:31:22 24 4
gpt4 key购买 nike

有什么方法可以扩展 ServiceHost 以便它接受工厂?

我想在不触及服务实现的情况下使用动态服务代理对 WCF 调用进行一些预处理。

编辑

现在 ServiceHost 创建看起来像

var host = new ServiceHost(typeof(MyService));

我想用类似的东西

var factory = new ServiceProxyFactory<MyService>();
var host = new MyServiceHost(typeof(MyService), factory);

最佳答案

我要找的接口(interface)是IInstanceProvider.

public class MyServiceInstanceProvider<TService> : IInstanceProvider where TService : new()
{

public object GetInstance(InstanceContext instanceContext, System.ServiceModel.Channels.Message message)
{
return ServiceFactory.Create<TService>();
}

public object GetInstance(InstanceContext instanceContext)
{
return ServiceFactory.Create<TService>();
}

public void ReleaseInstance(InstanceContext instanceContext, object instance)
{
return;
}
}

public class MyEndpointBehavior<TService> : IEndpointBehavior where TService : new()
{

public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
return;
}

public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
return;
}

public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
endpointDispatcher.DispatchRuntime.InstanceProvider = new MyServiceInstanceProvider<TService>();
}

public void Validate(ServiceEndpoint endpoint)
{
return;
}
}

public class MyServiceHost<TService> : ServiceHost where TService : new()
{
public MyServiceHost(params Uri[] baseAddresses)
:base(typeof(TService), baseAddresses)
{
}

public override System.Collections.ObjectModel.ReadOnlyCollection<ServiceEndpoint> AddDefaultEndpoints()
{
var endpoints = base.AddDefaultEndpoints();

foreach (var endpoint in endpoints)
{
endpoint.Behaviors.Add(new MyEndpointBehavior<TService>());
}

return endpoints;
}

public override void AddServiceEndpoint(ServiceEndpoint endpoint)
{
base.AddServiceEndpoint(endpoint);
endpoint.Behaviors.Add(new MyEndpointBehavior<TService>());
}

}

关于c# - 在 WCF ServiceHost 中提供工厂而不是类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7392100/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com