DkAngelito
DkAngelito

Reputation: 1187

Dependency Injection (using simple injector) on a WCF Service hosted in a Managed Windows Service

I'm creating a WCF service hosted on a Windows Service as explained here: https://msdn.microsoft.com/en-us/library/ms733069(v=vs.110).aspx.

My service has some dependencies.

Which would be the right way to apply DI here using Simple Inyector.

I read about the SimpleInjectorServiceHostFactory class here https://simpleinjector.readthedocs.org/en/latest/wcfintegration.html, but it appears that it only works for IIS hosted services.

On the 1st sample I assume that I register the types on the Main() method, but how should I create the ServiceBase?

And more important, how should I call (or create) the servicehost instance. Should I get the container from somewhere and directly create the instance of the real service using it. That seems pretty ugly for me

protected override void OnStart(string[] args)
{
    if (serviceHost != null)
    {
        serviceHost.Close();
    }

    // Create a ServiceHost for the CalculatorService type using the  
    // container directly
    serviceHost =  serviceHost = new ServiceHost(container.GetInstance<ICalculatorService>());

    serviceHost.Open();
}

Upvotes: 2

Views: 1939

Answers (1)

Anton Alstes
Anton Alstes

Reputation: 123

This blog post provides a possible approach: Decouple WCF Services from their DI Container with Common Instance Factory

The relevant code for creating the servicehost instance:

ServiceHost serviceHost;
var serviceBaseAddress = new Uri('http://localhost:8000/GreetingService');
switch (containerType)
{
    case ContainerType.Ninject:
        serviceHost = new NinjectServiceHost<GreetingService>
            (CreateNinjectContainer(), typeof(GreetingService), serviceBaseAddress);
        break;
    case ContainerType.SimpleInjector:
        serviceHost = new SimpleInjectorServiceHost<GreetingService>
            (CreateSimpleInjectorContainer(), typeof(GreetingService), serviceBaseAddress);
        break;
}

Upvotes: 0

Related Questions