我的第一个WCF服务器 - 为什么OperationContext.Current为null?

jav*_*red 4 c# wcf

我想实现我的第一个WCF回叫服务器.这是我的代码:

[ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(ILogCallback))]
public interface ILog
{
}

public interface ILogCallback
{
    [OperationContract(IsOneWay = true)]
    void Push(string callbackValue);
}

public class MyLog : ILog
{

}

class Log
{


    public static void initialize()
    {
        using (ServiceHost host = new ServiceHost(
            typeof (MyLog),
            new Uri[]
                {
                    new Uri("net.pipe://localhost")
                }))
        {

            host.AddServiceEndpoint(typeof (ILog),
                                    new NetNamedPipeBinding(),
                                    "PipeReverse");

            host.Open();
            // TODO: host.Close();
        }
    }

    public static void Push(string s)
    {
        ILogCallback callbacks = OperationContext.Current.GetCallbackChannel<ILogCallback>();
        callbacks.Push(s);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我尝试使用此代码使用我的服务器:

        Log.initialize();

        while (true)
        {
            Log.Push("Hello");
            System.Threading.Thread.Sleep(1000);
        }
Run Code Online (Sandbox Code Playgroud)

但我得到了NPE,因为OperationContext.Current为null.为什么,出了什么问题以及如何解决这个问题?

Pau*_*tos 14

因为您不在操作的上下文中.

您只是调用Log类的静态方法.

为了使您处于操作上下文中,您的调用必须来自您的WCF服务器正在服务的客户端.