46

我正在尝试将现有的 .NET Remoting 应用程序转换为 WCF。服务器和客户端共享公共接口,所有对象都是服务器激活的对象。

在 WCF 世界中,这类似于创建每次调用服务并ChannelFactory<T>用于创建代理。我正在为如何正确创建ChannelFactory<T>ASP.NET 客户端而苦苦挣扎。

出于性能原因,我想缓存ChannelFactory<T>对象并在每次调用服务时创建通道。在 .NET 远程处理的日子里,曾经有RemotingConfiguration.GetRegisteredWellknownClientTypes()一种方法可以获取一组客户端对象,然后我可以缓存这些对象。看来,在 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()方法。

另一个小问题是我是否需要ChannelFactory.Close()在 ASP.NET 应用程序结束后调用通道工厂对象的方法,或者我可以让 .NET 框架自行处理通道工厂对象。通过 using 方法调用服务方法后,代理通道将始终关闭((IChannel)proxy).Close()

4

4 回答 4

68

这是我用来处理通道工厂的辅助类:

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>
于 2010-07-08T05:57:25.753 回答
13

是的,如果你想创建这样的东西——一个包含所有这些ChannelFactory<T>实例的静态类——你必须确保这个类是 100% 线程安全的,并且在并发访问时不会出错。我还没有过多地使用 .NET 4 的功能,所以我无法具体评论这些功能 - 但我绝对会建议尽可能安全。

至于你的第二个(次要)问题: ChannelFactory 本身是一个静态类 - 所以你不能真正调用.Close()它的方法。如果您要问是否要.Close()在实际调用该方法IChannel,那么再次:是的,尽力成为一个好公民并尽可能关闭这些通道。如果您错过了一个,.NET 会处理它 - 但不要只是将您未使用的频道扔在地板上然后继续 - 自己清理!:-)

于 2010-07-08T05:22:48.847 回答
2

我不喜欢调用结构:

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 构建一些缓存。

连接类的代码:

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();
               }
            }
         }
      }
}
于 2011-04-29T14:34:47.840 回答
0

@NelsonRothermel,是的,我没有在 ChannelFactoryManager ChannelFaulted 事件处理程序中使用 try catch。所以 ChannelFaulted 会变成

 private void ChannelFaulted(object sender, EventArgs e)
    {
        IClientChannel channel = (IClientChannel)sender;            
        channel.Abort();
    }

似乎允许原始异常冒泡。还选择不使用 channel.close ,因为它似乎会引发异常,因为通道已经处于故障状态。FactoryFaulted 事件处理程序可能有类似的问题。顺便说一句@Darin,好一点的代码......

于 2014-05-30T09:14:05.443 回答