简体   繁体   English

如何将对象注入WCF服务

[英]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). 根据客户端的请求,它将调用UpdatePerson(aPersonIdentifier)。

I would like to talk to a database from UpdatePerson. 我想和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. 问题在于,我从未创建过UpdateService类的实例。 So how can I inject a dependency? 那么如何注入依赖项呢? How would you solve this? 您将如何解决?

Thanks, regards, Miel. 谢谢,问候,米尔。

Take a look at the IInstanceProvider interface. 看一下IInstanceProvider接口。 Basically you need to implement this interface and in the method GetInstance instantiate the WCF class yourself providing any dependencies. 基本上,您需要实现此接口,并在GetInstance方法中自行实例化WCF类,以提供任何依赖关系。

Basically you need to implement an IInstanceProvider based on your IOC container and an IServiceBehaviour that uses the instance provider you wrote. 基本上,您需要基于IOC容器和使用您编写的实例提供程序的IServiceBehaviour实现IInstanceProvider。 This will enable the IOC container to build up your object heirarchy for you. 这将使IOC容器能够为您建立对象层次结构。

There's an example implementation here 这里有一个示例实现

If you plan on injecting your dependencies, you should definitely consider using an IoC container. 如果计划注入依赖项,则绝对应该考虑使用IoC容器。 Eg Windsor. 例如温莎。

If you use Windsor, there is a WCF Integration Facility, that automatically injects all dependencies into your service. 如果使用Windsor,则有WCF集成工具,可自动将所有依赖项注入服务中。 Check it out here . 在这里查看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM