创建WCF ChannelFactory <T>

Eri*_*ric 45 .net c# wcf channelfactory c#-4.0

我正在尝试将现有的.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;
    }    
}
Run Code Online (Sandbox Code Playgroud)

我认为上面的代码可以工作,但我有点担心多个线程试图添加新ChannelFactory<T>对象,如果它不在查找中.由于我使用的是.NET 4.0,我首先考虑使用ConcurrentDictionary和使用GetOrAdd()方法或使用TryGetValue()方法来检查是否ChannelFactory<T>存在并且它不存在,然后使用GetOrAdd()方法.虽然ConcurrentDictionary.TryGetValue()ConcurrentDictionary.GetOrAdd()方法不确定性能.

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

Dar*_*rov 64

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

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();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我定义了一个服务调用者:

public interface IServiceInvoker
{
    R InvokeService<T, R>(Func<T, R> invokeHandler) where T: class;
}
Run Code Online (Sandbox Code Playgroud)

和实施:

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;
    }

}
Run Code Online (Sandbox Code Playgroud)

现在每次需要调用WCF服务时都可以使用:

WCFServiceInvoker invoker = new WCFServiceInvoker();
SomeReturnType result = invoker.InvokeService<IMyServiceContract, SomeReturnType>(
    proxy => proxy.SomeMethod()
);
Run Code Online (Sandbox Code Playgroud)

这假设您已IMyServiceContract在配置文件中为服务合同定义了客户端端点:

<client>
    <endpoint 
        name="myservice" 
        address="http://example.com/" 
        binding="basicHttpBinding" 
        contract="IMyServiceContract" />
</client>
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!这非常有趣,我需要对其进行更多分析。我有几个问题:您正在订阅ChannelFactory &lt;T&gt; .Faulted事件。有需要吗?该事件何时会触发并订阅Channel.Faulted足以检测故障状态? (2认同)
  • 当你订阅这个事件`((IClientChannel)local).Faulted + = ChannelFaulted`时,`return invokeHandler(arg);`行默认不会抛出异常.我想这就是为什么`抛出新的ApplicationException("Exc_ChannelFailure");`被添加了.有没有人找到了获得原始异常的方法? (2认同)

mar*_*c_s 13

是的,如果你想创建这样的东西 - 一个静态类来容纳所有这些ChannelFactory<T>实例 - 你必须确保这个类是100%线程安全的,并且在并发访问时不会绊倒.我还没有使用.NET 4的功能,所以我不能对这些功能发表评论 - 但我肯定会建议尽可能安全.

至于你的第二个(次要)问题:ChannelFactory本身是一个静态类 - 所以你不能真正调用.Close()它的方法.如果您打算询问是否.Close()在实际情况下调用该方法IChannel,那么请再次:是的,尽量做一个好公民并尽可能关闭这些渠道.如果你错过了一个,.NET会照顾它 - 但不要只是把未使用的频道丢在地板上继续 - 自己清理干净!:-)