wcf

[ServiceContract()]
interface IMyService
{
    [OperationContract()]
    void DoSomething();
}

public class MyService : IMyService
{
    public void DoSomething()
    {
        // do something
    }
}

原方

public class Test
{
    public void Test()
    {
        BasicHttpBinding myBinding = new BasicHttpBinding();
        EndpointAddress myEndpoint = new EndpointAddress("http://localhost/MyService/");
        ChannelFactory<imyservice> myChannelFactory = new ChannelFactory<imyservice>(myBinding, myEndpoint);
        IMyService pClient = myChannelFactory.CreateChannel();
        pClient.DoSomething();
        ((IClientChannel)pClient).Close();
    }
}

=====

public class Test
{
    public void Test()
    {
        //create client proxy from factory
        IMyService pClient = (IMyService)ClientFactory.CreateClient(typeof(IMyService));
        pClient.DoSomething();
        ((IClientChannel)pClient).Close();
    }
}
//Factory class for client proxy
public abstract class ClientFactory
{
    public static object CreateClient(Type targetType)
    {
        BasicHttpBinding binding = new BasicHttpBinding();
        //Get the address of the service from configuration or some other mechanism - Not shown here
        EndpointAddress addess = new EndpointAddress(GetAddessFromConfig(targetType));
        //dynamic factory generation
        object factory = Activator.CreateInstance(typeof
        (ChannelFactory<>).MakeGenericType(targetType), binding, address);
        MethodInfo createFactory = factory.GetType().GetMethod("CreateChannel", new Type[] { });
        //now dynamic proxy generation using reflection
        return createFactory.Invoke(factory, null);
    }
}

原文地址:https://www.cnblogs.com/zeroone/p/3659705.html