My WCF service uses callbacks. To be able to call all clients, I'm using something like this:
[ServiceBehavior (InstanceContextMode = InstanceContextMode.PerSession)]
class Svc
{
// stores all connections
private static List<Svc> Connections = new List<Svc> ();
// callback for this instance
private ICallback Cb;
public Svc ()
{
Cb = OperationContext.Current.GetCallbackChannel<ICallback> ();
Connections.Add (this);
}
// ... lots of other code that uses or updates the list of connections
}
Is this the right way to do it?
I'm asking because I'm fighting with an apparent design problem in the above approach. I tried to move a lot of common code, including the static List<Svc>
to a common base class that can be used by all my WCF services. But when deriving, this list is shared among all subclasses.开发者_JAVA百科
I then tried to avoid this undesirable sharing by making the base class generic (Svc<T>
, meaning each subclass gets its own static members) but this leads to other annoyances and is not a clean design.
Yes, this is the right approach of storing references to your clients to send callbacks to all of them. I don't store the CallbackChannel objects but the OperationContext instances in my service.
To your other question: You could extract the code to administrate the list of connected clients to a separate class and use an instance of that class in your service.
Use the Singleton pattern when you need to store global state in a centralized manner.
In your case it could look like this:
public Svc()
{
this.CallbackChannel = OperationContext.Current.GetCallbackChannel<ICallback>();
// The static 'Instance' property returns the singleton
SvcActiveInstanceContainer.Instance.Add(this);
}
Related resources:
- Singleton Design Pattern
精彩评论