WCF services without adding a service reference

 

One way to avoid the spaghetti code and awkward namespaces that arise from using the Add Service Reference in Visual Studio is to extract your service interface code (including any DTO’s) into a separate assembly and share this assembly between your projects. You can also do this by referencing the same code files if you don’t want to share the assembly. Doesn’t this produce tight coupling though? Not really - you are sharing an interface, not implementation – the fact that the interface is a CLR object or a few C# files rather than a WSDL file is incidental.

 

    public static class WcfServiceFactory
    {
        public static T BuildServiceProxy<T>(string serviceUri)
        {
            var basicHttpBinding = new BasicHttpBinding
                                       {
                                           MaxReceivedMessageSize = 2147483647,
                                           MaxBufferSize = 2147483647,
                                           SendTimeout = TimeSpan.FromMinutes(10),
                                           ReceiveTimeout = TimeSpan.FromMinutes(10)
                                       };

            var endpointAddress = new EndpointAddress(serviceUri);
            var service = new ChannelFactory<T>(basicHttpBinding, endpointAddress).CreateChannel();
            return service;
        }
    }

 

This is a sample WcfServiceFactory class you can use to create a proxy that can then be injected via your DI container (or however you decide to instantiate it).

Add a Comment