1

我们有一个WCF服务有多个客户端连接到它。

我们的服务已设置为每个实例服务。该服务需要访问另一个实例对象才能完成其工作。所需的实例不是 wcf 服务,我宁愿不将所需的实例设为单例。

如果服务是我创建的对象,那么我只需将它需要与之交互的实例对象传递给它。但由于这是一个由 wcf 创建的 wcf 服务。

如何挂钩服务的创建以向其传递一些要使用的数据/接口,或者如何在创建服务后获取指向服务的指针,以便将其传递给所需的实例。

[ServiceContract]    
public interface IMyService
{
    [OperationContract(IsOneWay = true)]
    void DoSomethingCool();
}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
class MyService : IMyService 
{
    private IHelper helper;
    void DoSomethingCool()
    {
        // How do I pass an instance of helper to MyService so I can use it here???
        helper.HelperMethod();
    }
}
4

2 回答 2

1

正如 Tim S. 建议的那样,您应该阅读依赖注入(从他的评论中,可以在此处找到链接http://msdn.microsoft.com/en-us/library/vstudio/hh273093%28v=vs.100%29。 .aspx)。Apoor mans dependency injection可以像这样使用:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
class MyService : IMyService 
{
    private IHelper _helper;

    public MyService() : this(new Helper())
    {

    }

    public MyService(IHelper helper)
    {
       _helper = helper;
    }

    void DoSomethingCool()
    {            
        helper.HelperMethod();
    }
}

如果你想要一个特定的实现,你需要一个 IoC ( Inversion of Control) 容器来解决这个依赖。有很多可用的,但特别是,我使用 Castle Windsor。

于 2013-10-24T17:12:33.200 回答
0

好的,我最终做的是制作一个单例 ServiceGlue 对象作为中介,而不是让我的助手类成为单例。

服务和助手都向作为单例的中介进行自我注册,并且单例来回传递实例。

在设置我的服务之前,我会实例化单例并注册帮助程序,以便每个服务都可以获得帮助程序对象。

这使我的代码看起来像:

public class ServiceGlue
{
    private static ServiceGlue instance = null;
    public static ServiceGlue Instance
    {
        get
        {
            if (instance == null)
                instance = new ServiceGlue();
             return instance;
         }
     }

    public Helper helper { get; set; }
}


[ServiceContract]    
public interface IMyService
{
    [OperationContract(IsOneWay = true)]
    void DoSomethingCool();
}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode =     ConcurrencyMode.Multiple)]
class MyService : IMyService 
{
    private IHelper helper;
    public MyService()
    {
       // use an intermidiary singleton to join the objects
       helper = ServiceGlue.Instance.Helper();
    }

    void DoSomethingCool()
    {
       // How do I pass an instance of helper to MyService so I can use it here???
       helper.HelperMethod();
    }
}
于 2013-10-24T18:52:26.640 回答