我正在尝试将现有的.NET远程应用程序转换为WCF。服务器和客户端共享公共接口,所有对象都是服务器激活的对象。
在WCF世界中,这类似于创建每个调用的服务并使用ChannelFactory<T>创建代理。我正在为如何正确地为ASP.NET客户端创建ChannelFactory<T>而苦苦挣扎。
出于性能原因,我希望缓存ChannelFactory<T>对象,并在每次调用服务时只创建通道。在.NET remoting时代,曾经有一个RemotingConfiguration.GetRegisteredWellknownClientTypes()方法来获取一组client对象,然后我可以对其进行缓存。似乎,在WCF世界中没有这样的东西,尽管我能够从配置文件中获得端点的集合。
下面是我认为可行的方法。我可以创建类似这样的东西:
public static ProxyHelper
{
static Dictionary<Type, object> lookup = new Dictionary<string, object>();
static public T GetChannel<T>()
{
Type type = typeof(T);
ChannelFactory<T> factory;
if (!lookup.ContainsKey(type))
{
factory = new ChannelFactory<T>();
lookup.Add(type, factory);
}
else
{
factory = (ChannelFactory<T>)lookup[type];
}
T proxy = factory.CreateChannel();
((IClientChannel)proxy).Open();
return proxy;
}
}我认为上面的代码可以工作,但是我有点担心多线程试图添加新的ChannelFactory<T>对象,如果它不在查找中。由于我使用的是.NET 4.0,所以我在考虑使用ConcurrentDictionary并使用GetOrAdd()方法,或者先使用TryGetValue()方法来检查ChannelFactory<T>是否存在,然后再使用GetOrAdd()方法。虽然不确定ConcurrentDictionary.TryGetValue()和ConcurrentDictionary.GetOrAdd()方法的性能。
另一个次要问题是,在ASP.NET应用程序结束后,是否需要在通道工厂对象上调用ChannelFactory.Close()方法,或者是否可以让.NET框架自行处理通道工厂对象。使用((IChannel)proxy).Close()方法调用服务方法后,代理通道始终处于关闭状态。
发布于 2010-07-08 13:22:49
是的,如果你想创建这样的东西--一个静态类来容纳所有的ChannelFactory<T>实例--你一定要确保这个类是100%线程安全的,并且在并发访问时不会出错。我还没有用过太多.NET 4的特性,所以我不能特别评论这些特性--但我绝对建议让它尽可能的安全。
至于你的第二个(次要)问题: ChannelFactory本身是一个静态类--所以你不能真的在它上面调用.Close()方法。如果你想问是否要在实际的IChannel上调用.Close()方法,那么再次:是的,尽你最大的努力做一个好公民,如果可以的话,关闭这些通道。如果你错过了一个,.NET会处理它的-但不要只是把你不用的频道扔在地上然后继续-自己清理!:-)
发布于 2010-07-08 13:57:26
下面是一个我用来处理通道工厂的助手类:
public class ChannelFactoryManager : IDisposable
{
private static Dictionary<Type, ChannelFactory> _factories = new Dictionary<Type,ChannelFactory>();
private static readonly object _syncRoot = new object();
public virtual T CreateChannel<T>() where T : class
{
return CreateChannel<T>("*", null);
}
public virtual T CreateChannel<T>(string endpointConfigurationName) where T : class
{
return CreateChannel<T>(endpointConfigurationName, null);
}
public virtual T CreateChannel<T>(string endpointConfigurationName, string endpointAddress) where T : class
{
T local = GetFactory<T>(endpointConfigurationName, endpointAddress).CreateChannel();
((IClientChannel)local).Faulted += ChannelFaulted;
return local;
}
protected virtual ChannelFactory<T> GetFactory<T>(string endpointConfigurationName, string endpointAddress) where T : class
{
lock (_syncRoot)
{
ChannelFactory factory;
if (!_factories.TryGetValue(typeof(T), out factory))
{
factory = CreateFactoryInstance<T>(endpointConfigurationName, endpointAddress);
_factories.Add(typeof(T), factory);
}
return (factory as ChannelFactory<T>);
}
}
private ChannelFactory CreateFactoryInstance<T>(string endpointConfigurationName, string endpointAddress)
{
ChannelFactory factory = null;
if (!string.IsNullOrEmpty(endpointAddress))
{
factory = new ChannelFactory<T>(endpointConfigurationName, new EndpointAddress(endpointAddress));
}
else
{
factory = new ChannelFactory<T>(endpointConfigurationName);
}
factory.Faulted += FactoryFaulted;
factory.Open();
return factory;
}
private void ChannelFaulted(object sender, EventArgs e)
{
IClientChannel channel = (IClientChannel)sender;
try
{
channel.Close();
}
catch
{
channel.Abort();
}
throw new ApplicationException("Exc_ChannelFailure");
}
private void FactoryFaulted(object sender, EventArgs args)
{
ChannelFactory factory = (ChannelFactory)sender;
try
{
factory.Close();
}
catch
{
factory.Abort();
}
Type[] genericArguments = factory.GetType().GetGenericArguments();
if ((genericArguments != null) && (genericArguments.Length == 1))
{
Type key = genericArguments[0];
if (_factories.ContainsKey(key))
{
_factories.Remove(key);
}
}
throw new ApplicationException("Exc_ChannelFactoryFailure");
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
lock (_syncRoot)
{
foreach (Type type in _factories.Keys)
{
ChannelFactory factory = _factories[type];
try
{
factory.Close();
continue;
}
catch
{
factory.Abort();
continue;
}
}
_factories.Clear();
}
}
}
}然后我定义了一个服务调用者:
public interface IServiceInvoker
{
R InvokeService<T, R>(Func<T, R> invokeHandler) where T: class;
}和一个实现:
public class WCFServiceInvoker : IServiceInvoker
{
private static ChannelFactoryManager _factoryManager = new ChannelFactoryManager();
private static ClientSection _clientSection = ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;
public R InvokeService<T, R>(Func<T, R> invokeHandler) where T : class
{
var endpointNameAddressPair = GetEndpointNameAddressPair(typeof(T));
T arg = _factoryManager.CreateChannel<T>(endpointNameAddressPair.Key, endpointNameAddressPair.Value);
ICommunicationObject obj2 = (ICommunicationObject)arg;
try
{
return invokeHandler(arg);
}
finally
{
try
{
if (obj2.State != CommunicationState.Faulted)
{
obj2.Close();
}
}
catch
{
obj2.Abort();
}
}
}
private KeyValuePair<string, string> GetEndpointNameAddressPair(Type serviceContractType)
{
var configException = new ConfigurationErrorsException(string.Format("No client endpoint found for type {0}. Please add the section <client><endpoint name=\"myservice\" address=\"http://address/\" binding=\"basicHttpBinding\" contract=\"{0}\"/></client> in the config file.", serviceContractType));
if (((_clientSection == null) || (_clientSection.Endpoints == null)) || (_clientSection.Endpoints.Count < 1))
{
throw configException;
}
foreach (ChannelEndpointElement element in _clientSection.Endpoints)
{
if (element.Contract == serviceContractType.ToString())
{
return new KeyValuePair<string, string>(element.Name, element.Address.AbsoluteUri);
}
}
throw configException;
}
}现在,每次您需要调用WCF服务时,您都可以使用以下代码:
WCFServiceInvoker invoker = new WCFServiceInvoker();
SomeReturnType result = invoker.InvokeService<IMyServiceContract, SomeReturnType>(
proxy => proxy.SomeMethod()
);这里假设您已经在配置文件中为IMyServiceContract服务契约定义了一个客户端端点:
<client>
<endpoint
name="myservice"
address="http://example.com/"
binding="basicHttpBinding"
contract="IMyServiceContract" />
</client>发布于 2011-04-29 22:34:48
我不喜欢调用结构:
WCFServiceInvoker invoker = new WCFServiceInvoker();
var result = invoker.InvokeService<IClaimsService, ICollection<string>>(proxy => proxy.GetStringClaims());此外,您不能使用同一通道两次。
我创建了这个解决方案:
using(var i = Connection<IClaimsService>.Instance)
{
var result = i.Channel.GetStringClaims();
}现在,您可以重用相同的通道,直到using语句调用dispose。
GetChannel方法基本上是一个ChannelFactory.CreateChannel(),带有一些我正在使用的额外配置。
您可以像其他解决方案一样为ChannelFactory构建一些缓存。
Connnection类的代码:
public static class Connection<T>
{
public static ChannelHolder Instance
{
get
{
return new ChannelHolder();
}
}
public class ChannelHolder : IDisposable
{
public T Channel { get; set; }
public ChannelHolder()
{
this.Channel = GetChannel();
}
public void Dispose()
{
IChannel connection = null;
try
{
connection = (IChannel)Channel;
connection.Close();
}
catch (Exception)
{
if (connection != null)
{
connection.Abort();
}
}
}
}
}https://stackoverflow.com/questions/3200197
复制相似问题