All WCF services has an attribute of the name “Factory” which usually has the value: ServiceHostFactory.
Factory that provides instances of ServiceHost in managed hosting environments where the host instance is created dynamically in response to incoming messages.
The managed hosting environments that support dynamic activation are Internet Information Services (IIS) and Windows Process Activation Service (WAS).
In Service Tier, Let’s take MyService.
<%@ ServiceHost Language="C#" Debug="true" Service="MyNameSpace.MyService, MyNameSpace.MyService" Factory="MyNameSpace.MyService.MyServiceHostFactory, MyNameSpace.MyService" %>
Its factory is MyServiceHostFactory.
UnityServiceHostFactory is a type available in Unity.Wcf.dll and it derives from ServiceHostFactory.
namespace Unity.Wcf
{
public abstract class UnityServiceHostFactory : ServiceHostFactory
{
protected abstract void ConfigureContainer(IUnityContainer container);
protected override ServiceHost CreateServiceHost(System.Type serviceType, Uri[] baseAddresses)
{
UnityContainer container = new UnityContainer();
this.ConfigureContainer(container);
return new UnityServiceHost(container, serviceType, baseAddresses);
}
}
}
When any service is launched it hits, the below method in the class “InjectionServiceHostFactory”.
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
try
{
ServiceHost serviceHost = base.CreateServiceHost(serviceType, baseAddresses);
serviceHost.Closed += new EventHandler(OnClosed);
serviceHost.Opened += new EventHandler(OnOpened);
serviceHost.Faulted += new EventHandler(OnFaulted);
return serviceHost;
}
catch (Exception e)
{
log.Error("Error encountered during service host creation", e);
throw;
}
}
It can be overrridden to any derived class we want, but here it is overridden max till InjectionServiceHostFactory.
This call in turn triggers ConfigureContainer(IUnity container) of the respective ServiceHostFactory class.
Here is the place where the dependencies are predefined and injected using Unity.