如何将对象注入WCF服务 [英] How to inject an object into a WCF service
问题描述
如果我有这样的服务定义/实现:
using System;
使用System.ServiceModel;
命名空间aspace.service
{
[ServiceContract(Namespace = http://aspace.service)]
公共接口IUpdate
{
[OperationContract]
ConfirmationMessage UpdatePerson(string PersonIdentifier);
}
}
公共类UpdateService:IUpdate
{
public ConfirmationMessage UpdatePerson(string PersonIdentifier)
{
//这里的一些实现
}
}
我可以创建一个服务主机,如下所示:
ServiceHost host = new ServiceHost(typeof(UpdateService),someEndpointAddress);
然后,在创建绑定并添加元数据行为之后,我可以打开主机。
我想与UpdatePerson的数据库进行通信。
回答我的上一个问题的建议,我应该对这种情况使用依赖注入问题。
问题是我从未创建过UpdateService类的实例。那么如何注入依赖项呢?
谢谢,问候,米尔。
看看 IInstanceProvider 接口。基本上,您需要实现此接口,并在方法 GetInstance 中实例化WCF自己提供任何依赖项。
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.
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.
这篇关于如何将对象注入WCF服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!