Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

my first WCF Server - why OperationContext.Current is null?

Tags:

c#

wcf

I'm tring to implement my first WCF call-back server. This is my code:

[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);
    }
}

then I try to use my server using this code:

        Log.initialize();

        while (true)
        {
            Log.Push("Hello");
            System.Threading.Thread.Sleep(1000);
        }

But I got NPE, because OperationContext.Current is null. Why, what's wrong and how to fix that?

like image 474
Oleg Vazhnev Avatar asked Dec 03 '22 07:12

Oleg Vazhnev


2 Answers

Because you are NOT in the context of an operation.

You're simply calling a static method of the Log class.

For you to be in an Operation Context your call MUST have been come from a client that is being serviced by your WCF server.

like image 172
Paulo Santos Avatar answered Dec 15 '22 12:12

Paulo Santos


OperationContext.Current is a thread-static property that is initialized when request arrives to the server. Here's what you do to call the callback

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

public class MyLog : ILog
{
  void PushOnTheClient()
  {
        ILogCallback callbacks = OperationContext.Current.GetCallbackChannel<ILogCallback>();
        callbacks.Push(s);
  }
}
like image 21
Dmitry Ornatsky Avatar answered Dec 15 '22 10:12

Dmitry Ornatsky