WCF duplex: calling callback outside class of WCF-service - c#

I develop WCF-service with duplex mode and use nettcpbinding. I use .NET 4.5. I have only one client and only one server and there is a lot of logic between its. The client always the first begins communication with the server. I want that server can call client functions outside WCF-service class. I try to use duplex mode for this purpose.
This is my WCF-service:
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single, InstanceContextMode = InstanceContextMode.Single)]
public class Service : IService
{
...
public IServiceCallback Callback
{
get
{
return OperationContext.Current.GetCallbackChannel<IServiceCallback>();
}
}
}
I have no problem when I call my callback within OperationContract functions of my service:
Callback.foo();
But when I try to call it outside class Service for example:
service = new Service();
service.Callback.foo();
I got NullReferenceException of OperationContext.Current. I found a lot of information about the similar problems on the SO and other resources but it can't help to decide my problem.
Are there any solutions of my issue or may be workarounds for calling of callback? At the moment I plan to create one more WCF-service for my purpose but I feel that this is bad solution. Thanks for attention.

OperationContext.Current has a meaning only when it runs from the same thread that handles the current client request. You did not specify where exactly you calls this from.

Related

How to notify the host of a WCF service when a client connects?

I have a WCF service that is hosted by a windows service. I can't figure out how to inform the windows service when a client connects to the WCF service. Basically all I have in the windows service to start the WCF service is this:
private ServiceHost sHost;
WCF.WCFService wcfService = new WCF.WCFService();
sHost = new ServiceHost(wcfService);
sHost.Open();
I am able to call methods in the WCF service with the windows service using the wcfService object. Is there some way to have some kind of event that would fire when a client connects to WCF service?
The service runs as an object which is instantiated according to the ServiceBehaviourAttribute property InstanceContextMode
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class MyService : IMyService
{
// ...
The values for InstanceContextMode are
Single - a single instance of the service runs for all sessions and calls
PerSession - an instance of the service runs for each session (i.e. each client)
PerCall - an instance of the service is instantiated for each call, even from a single client
The default value is PerSession, and this makes sense for most scenarios. Assuming you're using PerSession, you can put whatever 'connect logic' you like inside the constructor for the service.
// you don't need to specify PerSession as it is default, but I have for clarity
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class MyService : IMyService
{
public MyService()
{
// constructor will be called for each new client session
// eg fire an Event, log a new client has connected, etc
}
// ...
}
You need to be careful running code in the constructor, because the service will not be available until the constructor has completed. If you want to do anything that may take time, fire an event or send a thread to perform that work.
I found the best answer here: Subscribe to events within a WCF service
As suspected you can create an event handler in the WCF service that can be picked up by the host.

How to call a WCF singleton service within a WCF singleton service without hanging?

I have two services, one that calls another. Both are marked as singletons as follows:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,
ConcurrencyMode = ConcurrencyMode.Multiple)]
public class Service : IService
And I set these up with a ServiceHost as follows:
ServiceHost serviceHost = new ServiceHost(singletonElement);
serviceHost.Open();
When the parent service tries to call the child service on the same machine, the parent service hangs, waiting for the child service.
I'm already considering moving away from the singleton model, but is there anything wrong with my approach? Is there an explanation for this behavior and a way out of it?
The parent service hangs it because might be becoz the child service method is taking too long. If it takes long time to return call it asyncronously or make child servcie method IsOneWayo=True in the OpearationContract arrtribute.
One way service is Fire & Forget kind of call it does not return any value.
The problem was that I was hosting within a WPF application and did not set UseSynchronizationContext to false. This makes the WCF service host in the UI thread, thus causing a deadlock when you have one service (on the UI thread) calling another service (also on a UI thread).

WCF: Is there a way to return an object that is able to execute on the server?

Coming from a Java background, this is the way I'm thinking:
The server provides an object to the client. This object should be able to execute on the server.
Server:
private string _S = "A";
public interface IFoo { void Bar(); }
private class Foo : IFoo {
void Bar() { _S = "B";}
}
public IFoo GetFoo() { return new Foo(); }
Client:
IFoo foo = serverChannel.GetFoo();
foo.Bar();
Is this possible? Or is my understanding wrong and this is not how it works in WCF? What would be a better design?
No, I don't think that'll work. You see: WCF is not some kind of a remoting, remote-object, or remote-procedure call mechamism.
WCF at its core is a messaging infrastructure. Your client make a call to a method on a client-side proxy; the WCF runtime on the client captures the input parameters and the method name and a few more bits and pieces, serializes them into a message (either text or binary), and send that message across the wire (using whatever transport you like). The server does the same thing in reverse, deserializes the message, instantiantes a service class, executes a method on that class, and packages the return values back into a serialized message.
But there's really no connection or remoting link between client. Anything that goes between the two has to be serializable - into XML text at its core. You can pass around concrete classes and so on - but you cannot pass around interface, object references etc.
No - you cannot send objects around. As marc_s pointed out, WCF is a message-oriented communications framework.
But, you do have different instancing options.
By default, Windows Communication Foundation instantiates services on a per-call basis: a service instance, a common language runtime (CLR) object, exists only while a client call is in progress. Every client request gets a new dedicated service instance. This is something like Stateless Session Beans in J2EE.
Another option is session-based activation, which is something like Stateful Session Beans in J2EE. Using this approach, when the client creates a new proxy to a service configured as session-aware, WCF activates a new service instance and attaches it to the session. Every message sent by the client over that proxy will go to the same instance on the server side.
This activation behavior is selectable with the ServiceContract attribute.
Juval Lowy has written a good article on instantiation options in WCF.
Within these instancing options, you may find something that works for you.

Can an WCF Service create his own host?

I have a client / server type of application and I'd like the server object to create his own host. It looks something like this:
public class Server : IServer {
private ServiceHost m_Host;
public Server() {
m_Host = new ServiceHost(this);
m_Host.Open();
}
}
It seems to work fine when there are few message transfers occurring. But when it starts to speed up (my application requires that data is transfered every 50 ms), the server hangs and and the transfers stop after a few seconds without throwing an exception.
So, is it possible for an object to create his own host? Or do I really have to create it in the main() or do something else?
EDIT: I think the problem in this case is that I want the object that implements the service itself to create his own ServiceHost.
There's nothing really stopping any object to create an instance of ServiceHost.
The big question then is - can you guarantee that your object containing the service host is "alive"? Or was it garbage collected by any chance?
We use Windows (NT) Services to host our own custom service host classes to provide around-the-clock availability for WCF services - works just fine.
Marc
To be a WCF service it simply needs to implement the service contract. There's nothing to stop you adding more methods to open and close an instance of itself as a service.
Check out the ServiceBehaviorAttribute which allows you to specify how your service ... behaves. ;) The ConcurrencyMode property defined the support for multithreading and defaults to single threaded mode, and the InstanceContextMode defines if the service object is per session, per call or singleton.
Quote from ConcurrencyMode:
Setting ConcurrencyMode to Single instructs the system to restrict instances of the service to one thread of execution at a time, which frees you from dealing with threading issues. A value of Multiple means that service objects can be executed by multiple threads at any one time. In this case, you must ensure thread safety.
Quote from InstanceContextMode:
If the InstanceContextMode value is set to Single the result is that your service can only process one message at a time unless you also set the ConcurrencyMode value to Multiple.
We could really use some code examples of your service to further debug the behavior you're describing. For example, is your service object expensive to construct (assuming non singleton implementation), or do the operation slow down? Do you know where the time is spent, is it code, or could it as well be some firewall that limits connection? What protocol do you use?

WCF: Callback is not asynchronous

I'm trying to program a client server based on the callback infrastructure provided by WCF but it isn't working asynchronously.
My client connects to the server calling a login method, where I save the clients callback channel by doing
MyCallback callback =
OperationContext.Current.GetCallbackChannel<MyNamespace.MyCallback>()
After that the server does some processing and uses the callback object to communicate with the client.
All this works, the problem resides on the fact that even though I've set the method in the OperationContract as IsOneWay=true, the server still hangs when doing the call to the client.
I've tested this by launching the server for debug in the Visual Studio, detaching it, launching the client, calling the above mentioned login method, putting a break point in the implemented callback method of the client, and making the server send a response to the client. The server stops doing what it's supposed to do, waiting for the response of the client.
Any help is appreciated.
The trick is, to call the callback asynchronously from the server. Look at this:
[OperationContract(IsOneWay = true, AsyncPattern = true)]
IAsyncResult BeginOnMessageReceived(LiveDataMessage message, AsyncCallback acb, object state);
void EndOnMessageReceived(IAsyncResult iar);
I think the sollution to your problem is to properly set the 'ConcurecyMode' and 'Instance ContextMode' attributes for your service. To do that you must decorate your service declaration with those attributes as shown in the exemple below:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Reentrant)]
public class SubscriberService: ISubscriberServiceContract
{...}
InstanceContextMode.Single builds your service as a Singleton object so there is only one instance of your service running for all clients;
ConcurencyMode.Reentrant or ConcurencyMode.Multiple enables multithreaded work for the service instance. For 'Multiple' you must take care of thread syncronization in your service.
Did you try to set
[CallbackBehavior(UseSynchronizationContext = false)]
on the client side object implementing the callback interface ?

Categories

Resources