My first WCF server - why is OperationContext.Current NULL?

I am trying to implement my first WCF callback 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'm trying 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 is wrong and how to fix it?

+4
source share
3 answers

Because you are NOT in the context of an operation.

You simply call the static method of the Log class.

For you to be in the context of the operation, your call MUST be received from the client served by your WCF server.

+14
source

OperationContext.Current is a stream-static property that is initialized when a request arrives at the server. Here what you do to call a 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); } } 
+1
source

You are missing a subscription subscription. The way you do this is to create the [oneway] operation in your MyLog WCF server, calling it something like: " void SendMeLogs() ". This will open the client callback channel. Then you need to implement SendMeLogs() in lines of something like:

 void SendMeLogs() { while(CheckLogsForNewData()) { PushOnTheClient(); } } 

Since the SendMeLogs() function is enabled, the client will not block, but will begin subscribing to your log server. (you can search the web for sample code for a duplex calculator in wcf for a good example of this architecture). The key, however, is that you must have a good unsubscribe method, such as StopSendingMeLogs , to break the loop, and also make the PushOnTheClient function secure if the client terminates or connects to a specific client. The function " CheckLogsForNewData " should ideally be a common (static) implementation in your case

+1
source

All Articles