当前位置:首页 > Windows程序 > 正文

C#动态调用WCF接口

2021-03-26 Windows程序

public interface IServiceInvoker

    {

        void InvokeService<T>(Action<T> invokeHandler) where T : class;

        TReslt InvokeService<T, TReslt>(Func<T, TReslt> invokeHandler) where T : class;

    }

 

public class WCFServiceInvoker:IServiceInvoker

    {

        private static readonly ChannelFactoryManager FactoryManager = new ChannelFactoryManager();

 

        private static readonly ClientSection ClientSection =

            ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;

 

 

        public void InvokeService<T>(Action<T> invokeHandler) where T : class

        {

            KeyValuePair<string, string> endpointNameAddressPair = GetEndpointNameAddressPair(typeof(T));

            var arg = FactoryManager.CreateChannel<T>(endpointNameAddressPair.Key, endpointNameAddressPair.Value);

            var obj2 = (ICommunicationObject)arg;

            try

            {

                invokeHandler(arg);

            }

            finally

            {

                try

                {

                    if (obj2.State != CommunicationState.Faulted)

                    {

                        obj2.Close();

                    }

                }

                catch

                {

                    obj2.Abort();

                }

            }

        }

 

 

        public TReslt InvokeService<T, TReslt>(Func<T, TReslt> invokeHandler) where T : class

        {

            KeyValuePair<string, string> endpointNameAddressPair = GetEndpointNameAddressPair(typeof(T));

            var arg = FactoryManager.CreateChannel<T>(endpointNameAddressPair.Key, endpointNameAddressPair.Value);

            var obj2 = (ICommunicationObject)arg;

            try

            {

                return invokeHandler(arg);

            }

            finally

            {

                try

                {

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/68028.html