I am trying to set up a Publish/Subscribe system using WCF and where the WCF server is in a Windows service. The binding is net.TCP. The service is providing a \"Subscribe
I had a similar issue: in my case when the InstanceContextMode
was set to Single
the WebOperationContext.Current
was null
in the constructor. However it was available within the services/classes methods.
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.
In my case it was me being stupid...
I tried to set
callback = OperationContext.Current.GetCallbackChannel<IWcfSubscriberContract>();
In the CALLBACK function, instead of the server side funciton... When in callback function - obviously there's no current context.