Tired of Service References? Want to use dependency injection (IoC)? Ninject Extensions for WCF Clients lets you bind your service interfaces to a WCF service channel with a single line of code for each interface.
-
If you haven't already, add Ninject to your client project.
-
Reference Ninject.Extensions.Wcf.Client in your client project. Available on Nuget.
-
Ensure your service contracts (interfaces only) and data contracts (interfaces and implementations) are in a library referenced by both your client and server projects.
-
Ensure your client's Web.config or App.config has an endpoint for each service.
-
Add the following code to your client's NinjectModule:
using Ninject.Extensions.Wcf.Client; ... Bind<IMyService1>().ToServiceChannel(); Bind<IMyService2>().ToServiceChannel();
-
Consume the service:
private readonly IMyService1 myService1; public SomeClass(IMyService1 myService1) { this.myService1 = myService1; } ... myService1.DoSomething(); // Calls the service method over a WCF channel
And that's it! No Service References required. Have a look at the example projects if you like.
-
If your client is a web project, preferably use InRequestScope:
Bind<IMyService1>().ToServiceChannel().InRequestScope();
-
The channel object returned when Ninject resolves a service interface is NOT thread-safe, and will eventually timeout:
// DO NOT DO THIS Bind<IMyService1>().ToServiceChannel().InSingletonScope(); // VERY BAD IDEA
-
If you have multiple endpoints in your Web.config or App.config for the same service contract, you can bind by name:
Bind<IMyService1>().ToServiceChannel("IMyService1_BasicHttpBinding");
Similarly, you can use other overloads to programmatically specify an endpoint.