Resolving wcf service instances with an IoC container
February 7, 2010 4 Comments
In wcf, services are created and disposed by the wcf runtime through an IInstanceProvider implementation. The default implementation calls the parameterless constructor of the service. The easiest way to provide our own IInstanceProvider is to add a behavior to our service host by using an IServiceBehavior.
We can achieve our goal as simple as this:
public sealed class IoCInstanceProvider : IInstanceProvider { private readonly Type serviceType; public IoCInstanceProvider(Type serviceType) { this.serviceType = serviceType; } public object GetInstance(InstanceContext instanceContext) { return GetInstance(instanceContext, null); } public object GetInstance(InstanceContext instanceContext, Message message) { return IoC.Current.Container.Resolve(this.serviceType); } public void ReleaseInstance(System.ServiceModel.InstanceContext instanceContext, object instance) { if (instance is IDisposable) (instance as IDisposable).Dispose(); } }
The IoC class is just a singleton I use that exposes an Inversion of Control container like Unity.
