Wednesday, October 18, 2017

Using Ninject in a Self-Hosted environment, e.g. a Windows Service

Windows Services are a great way to host WCF, typically in scenarios where on-premise services are a requirement. As Dependency Injection becomes a standard practice in large scale systems, it can be hard to choose the right DI container. One of my personal favourites in Ninject because of its (typical) ease of configuration. Some benchmarks will show that Ninject isn't the fastest container out there in terms of constructing objects, but in practical use I've never once found that to be a problem.

The following example shows a function that can be used in a Windows Service for setting up Ninject to create ServiceHost instances in a self-hosting scenario:

private static NinjectServiceHost CreateServiceHost(IKernel standardKernel, Type serviceType)
{
 if (standardKernel == null)
 {
  throw new ArgumentNullException("standardKernel");
 }
 
 if (serviceType == null)
 {
  throw new ArgumentNullException("serviceType");
 }
 
 NinjectServiceHost ninjectServiceHost = new NinjectServiceHost(
  serviceBehavior: new NinjectServiceBehavior(
   instanceProviderFactory: type => new NinjectInstanceProvider(type, standardKernel),
   requestScopeCleanUp: new WcfRequestScopeCleanup(true)
   ),
  serviceType: serviceType
 );
 
 return ninjectServiceHost;
}

This function will be good enough to boot strap your services in your Windows ServiceBase
implementation in the vast majority of cases. You need only pass in your pre-configured 
IKernel instance and the Type of the WCF Service implementation.

No comments: