views:

184

answers:

3

Hi,

If I have a service definition/implementation like this:

using System;
using System.ServiceModel;

namespace aspace.service
{
  [ServiceContract(Namespace = "http://aspace.service")]
  public interface IUpdate
  {
    [OperationContract]
    ConfirmationMessage UpdatePerson(string PersonIdentifier);
  }
}

public class UpdateService : IUpdate
{
    public ConfirmationMessage UpdatePerson(string PersonIdentifier)
    {
        // some implementation here
    }
}

I can create a servicehost like this:

ServiceHost host = new ServiceHost(typeof(UpdateService), someEndpointAddress);

Then, after creating a binding and adding metadatabehavior, I can open the host. Which will, upon a request from a client, call UpdatePerson(aPersonIdentifier).

I would like to talk to a database from UpdatePerson. Answers to a previous question of mine suggest I should use dependency injection for this sort of thing.

The problem is that I never create an instance of the class UpdateService. So how can I inject a dependency? How would you solve this?

Thanks, regards, Miel.

+1  A: 

Take a look at the IInstanceProvider interface. Basically you need to implement this interface and in the method GetInstance instantiate the WCF class yourself providing any dependencies.

Darin Dimitrov
A: 

If you plan on injecting your dependencies, you should definitely consider using an IoC container. E.g. Windsor.

If you use Windsor, there is a WCF Integration Facility, that automatically injects all dependencies into your service. Check it out here.

mookid8000
+1  A: 

Basically you need to implement an IInstanceProvider based on your IOC container and an IServiceBehaviour that uses the instance provider you wrote. This will enable the IOC container to build up your object heirarchy for you.

There's an example implementation here

Steve Willcock
+1 because the example helped me to understand the code behind the links in the accepted answer
Miel