WCF - Inject the Unity Container into the per call self host service
Sometime you don't want use a singleton for sharing the transient data between per call services. Therefore you need to use the Unit Container to inject the dependencies to your service. Here is the sample of how to do it.Main Code :
UnityServiceHostFactory wFactory = new UnityServiceHostFactory(); try { ServiceHost wIosServiceHost = wFactory.CreateServiceHostWithType(typeof(DataAccessService)); wIosServiceHost.Open(); Console.WriteLine("running on endpoints:"); foreach (var wServiceEndpoint in wIosServiceHost.Description.Endpoints) { Console.WriteLine(wServiceEndpoint.Address.ToString()); Console.WriteLine("running"); } } catch (Exception ex) { ...
}
UnityServiceHostFactory :
UnityServiceHostFactory :
public class UnityServiceHostFactory : ServiceHostFactory { private static IUnityContainer mContainer;
public UnityServiceHostFactory()
{
// create you container and register all the types
mContainer = new UnityContainer(); mContainer.RegisterType<DataAccess>(); ... } protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) { return new UnityServiceHost(mContainer, serviceType, baseAddresses); }
public ServiceHost CreateServiceHostWithType(Type serviceType, Uri[] baseAddresses) { return new UnityServiceHost(mContainer, serviceType, baseAddresses); } public ServiceHost CreateServiceHostWithType(Type serviceType) { return new UnityServiceHost(mContainer, serviceType); }
}
UnityServiceHost :
public partial class UnityServiceHost : ServiceHost { public UnityServiceHost(IUnityContainer container, Type serviceType, params Uri[] baseAddresses) : base(container.Resolve(serviceType), baseAddresses) { } public UnityServiceHost(IUnityContainer container, Type serviceType) : base(container.Resolve(serviceType)) { } }
After trying like 10 different blog versions to integrate DI with a self-hosted WCF, yours is the first to work fully.
ReplyDeleteThanks a lot mate!
Great!
ReplyDeleteFacing one issue, I. E it is forcing me to change the instance context mode to Single but I need it for PerCall.
Any help is appreciated.
Delete