Miel
Miel

Reputation: 3477

How to inject an object into a WCF service

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.

Upvotes: 2

Views: 2351

Answers (3)

Steve Willcock
Steve Willcock

Reputation: 26899

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

Upvotes: 2

mookid8000
mookid8000

Reputation: 18628

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.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039418

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.

Upvotes: 2

Related Questions