I want inject a implementation of my Interface in the WCF but I want initialize my container of Dependency Injection in the Client of the WCF. So I can have a different implementation for each client of the my service.
Help me please.
I want inject a implementation of my Interface in the WCF but I want initialize my container of Dependency Injection in the Client of the WCF. So I can have a different implementation for each client of the my service.
Help me please.
When you use svcutil.exe or the Add Service Reference wizard in Visual Studio, one of the many types auto-generated will be a client interface. Let's call it IMyService
. There will also be another auto-generated interface called something like IMyServiceChannel
that implements IMyService and IDisposable. Use this abstraction in the rest of your client application.
Since you want to be able to create a new channel and close it again, you can introduce an Abstract Factory:
public interface IMyServiceFactory
{
IMyServiceChannel CreateChannel();
}
In the rest of your client application, you can take a dependency on IMyServiceFactory:
public class MyClient
{
private readonly IMyServiceFactory factory;
public MyClient(IMyServiceFactory factory)
{
if (factory == null)
{
throw new ArgumentNullException("factory");
}
this.factory = factory;
}
// Use the WCF proxy
public string Foo(string bar)
{
using(var proxy = this.factory.CreateChannel())
{
return proxy.Foo(bar);
}
}
}
You can create a concrete implementation of IMyServiceFactory that wraps WCF's ChannelFactory<T>
as an implementation:
public MyServiceFactory : IMyServiceFactory
{
public IMServiceChannel CreateChannel()
{
return new ChannelFactory<IMyServiceChannel>().CreateChannel();
}
}
You can now configure your DI Container by mapping IMyServiceFactory to MyServiceFactory. Here's how it's done in Castle Windsor:
container.Register(Component
.For<IMyServiceFactory>()
.ImplementedBy<MyServiceFactory>());
Bonus info: Here's how to wire up a WCF service with a DI Container.
Ok, but How I do to inject in service a custom implementation of a class? Example: public interface ISendMail{ seng(string subject, string message, string to); }. I want implement a class different for each client and in the client I inject this implementation in the WCF Service