How to inject an object into a WCF service

2019-07-16 04:10发布

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.

3条回答
贼婆χ
2楼-- · 2019-07-16 04:49

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

查看更多
叛逆
3楼-- · 2019-07-16 04:54

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.

查看更多
The star\"
4楼-- · 2019-07-16 05:08

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.

查看更多
登录 后发表回答