如何将对象注入WCF服务

时间:2009-05-19 09:07:24

标签: c# wcf dependency-injection

如果我有这样的服务定义/实现:

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
    }
}

我可以像这样创建一个服务主机:

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

然后,在创建绑定并添加metadatabehavior后,我可以打开主机。根据客户的请求,将调用UpdatePerson(aPersonIdentifier)。

我想和UpdatePerson的数据库交谈。 a previous question of mine的答案建议我应该使用依赖注入来处理这类事情。

问题是我从不创建UpdateService类的实例。那么如何注入依赖?你会如何解决这个问题?

谢谢,问候,Miel。

3 个答案:

答案 0 :(得分:2)

查看IInstanceProvider界面。基本上你需要实现这个接口,并且在方法GetInstance中自己实例化WCF类,提供任何依赖。

答案 1 :(得分:2)

基本上,您需要基于您的IOC容器和使用您编写的实例提供程序的IServiceBehaviour实现IInstanceProvider。这将使IOC容器能够为您构建对象层次结构。

有一个example implementation here

答案 2 :(得分:0)

如果您计划注入依赖项,则应该考虑使用IoC容器。例如。温莎。

如果您使用Windsor,则会有一个WCF集成工具,它会自动将所有依赖项注入您的服务。请查看here

相关问题