current OperationContext is null in WCF Windows Service

In the client code neither proxy created not channel factory. Service class instance is created as a class library.

You should consume service as below code

 ServiceCallback serviceCallback = new ServiceCallback();
 InstanceContext instanceContext = new InstanceContext(serviceCallback);

 var pubsubProxy = new PubSubProxy.WcfPublisherContractClient(instanceContext);
 pubsubProxy.Subscribe();

And when the service is running, OperationContext is created and you can access OperationContext.Current


I've faced this issue and non of the solutions worked and Most Important thing is if you're using

async await 
OperationContext.Current; will be null

My usage is to get Ip so used it like this before any awaitable call

var clientIpAddress = System.Web.HttpContext.Current?.Request?.UserHostAddress;

After the first await statement in your async service operation, OperationContext.Current could be null because the rest of the method body may be running on a different thread (and OperationContext does not flow between threads

So to get it you can write your code before any awaitable action

May be it'll help someone :)


As discussed in the comments, if you directly create an instance of the service type - as opposed to a WCF proxy/clientchannel - and then you call a method on it, there is no OperationContext. WCF provides an OperationContext instance when your operation is running within a service.