C# 如何在当前上下文中访问 WCF 服务实例?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1062469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 07:19:02  来源:igfitidea点击:

How do I get access to the WCF service instance in the current context?

c#.netwcf

提问by Nathan Ridley

If I am executing within the context of a particular service instance and operation, how do I get access to the currently-executing service instance? Service instances don't inherit from any specific common base class or interface and the only pathway into the existing context that I can find is:

如果我在特定服务实例和操作的上下文中执行,我如何访问当前正在执行的服务实例?服务实例不从任何特定的公共基类或接口继承,我能找到的进入现有上下文的唯一途径是:

OperationContext.Current

but I can't seem to find any properties that reference the actual service instance itself so that I can cast it to what I know it should be and perform operations on it.

但我似乎无法找到任何引用实际服务实例本身的属性,以便我可以将其转换为我认为应该是的内容并对其执行操作。

Without exploring why I am doing this (it's irrelevant), please let me know if there is any way to find the reference I am looking for.

在不探索我为什么这样做的情况下(这无关紧要),请告诉我是否有任何方法可以找到我正在寻找的参考资料。

EDIT:

编辑:

[ServiceContract]
public interface IInventory
{
    [OperationContract]
    List<DealInfo> ListDeals(DealQueryOptions options);
}

// This is the object I will need access to the current instance of
public class Inventory : ServiceBase<Inventory>, IInventory
{
    public List<DealInfo> ListDeals(DealQueryOptions options)
    {
        var obj = new Whatever(); // see below
    }
}

public class Whatever
{
    public Whatever()
    {
        // how do I get access to the service instance here?
        // assume that in this context we are not allowed to
        // pass the service instance to this class; this class
        // must automatically discover the instance itself.
    }
}

采纳答案by Nathan Ridley

var myService = OperationContext.Current.InstanceContext.GetServiceInstance();

回答by Krzysztof Kozmic

OperationContext.Currentshould have a property for this IIRC

OperationContext.Current应该有这个 IIRC 的属性