WCF central service with multiple clients - wcf

i can't find any good architecture explanation of how can WCF SHOULD be part of a main-server with multiple clients.
in my solution, i want to have a central WCF service (hosted in windows-service on windows server machine).
The central service is the only one that's connected to the DB.
all the clients, are connecting to this main service, login, and get having a duplex communication.
via that main service, one client can connect another one. or when one client using the main service to change the DB, the main service updates all other clients.
for doing that, i added in the main service the InstanceContextMode.Single attribute, and in the windows-service, i init ServiceHost with the WCF-service singleton.
it works. so so..
i can continue and search where the problems are, and how to fix them, but it looks like something here is not right, like i'm not supposed to do it this way.
i could really use an advice on how WCF service should be used as a main service with multiple clients, that require common memory.
it's basically for ~20 clients with not too intensive operations, but i still want the option to let them all communicate simultaneously with the main service, and not only one by one.

Related

Should I Open and Close my WCF client after each service call?

I have developed a WCF service for consumption within the organization's Ethernet.
The service is currently hosted on a windows-service and is using net.tcp binding.
There are 2 operation contracts defined in the service.
The client connecting to this service is a long running windows desktop application.
Employees(>30,000) usually have this client running throughout the week from Monday morning to Friday evening straight.
During this lifetime there might be a number of calls to the wcf service in question depending on a certain user action on the main desktop client.
Let us just say 1 in every 3 actions on the main desktop application would
trigger a call to our service.
Now we are planning to deploy this window service on each employee's desktop
I am also using `autofac` as the dependency resolver container.
My WCF service instance context is `PerSession`, but ideally speaking we have both the client and service running in the same desktop (for now) so I am planning to inject the same service instance for each new session using `autofac` container.
Now am not changing the `InstanceContext` attribute on the service implementation
because in future I might deploy the same service in a different hosting environment where I would like to have a new service object instance for each session.
Like mentioned earlier the client is a long running desktop application and I have read that it is a good practise to `Open` and `Close` the proxy for each call but if I leave the service to be PerSession it will create a new service instance for each call, which might not be required given the service and client have a 1-1 mapping. Another argument is that I am planning to inject the same instance for each session in this environment, so Open & Close for each service call shouldn't matter ?
So which approach should I take, make the service `Singleton` and Open Close for each call or
Open the client-side proxy when the desktop application loads/first service call and then Close it only when the desktop application is closed ?
My WCF service instance context is PerSession, but ideally speaking we have both the client and service running in the same desktop (for now) so I am planning to inject the same service instance for each new session using autofac container
Generally you want to avoid sharing a WCF client proxy because if it faults it becomes difficult to push (or in your case reinject) a new WCF to those parts of the code sharing the proxy. It is better to create a proxy per actor.
Now am not changing the InstanceContext attribute on the service implementation because in future I might deploy the same service in a different hosting environment where I would like to have a new service object instance for each session
I think there may be some confusion here. The InstanceContext.PerSession means that a server instance is created per WCF client proxy. That means one service instance each time you new MyClientProxy() even if you share it with 10 other objects being injected with the proxy singleton. This is irrespective of how you host it.
Like mentioned earlier the client is a long running desktop application and I have read that it is a good practise to Open and Close the proxy for each call
Incorrect. For a PerSession service that is very expensive. There is measurable cost in establishing the link to the service not to mention the overhead of creating the factories. PerSession services are per-session for a reason, it implies that the service is to maintain state between calls. For example in my PerSession services, I like to establish an expensive DB connection in the constructor that can then be utilised very quickly in later service calls. Opening/closing in this example essentially means that a new service instance is created together with a new DB connection. Slow!
Plus sharing a client proxy that is injected elsewhere sort of defeats the purpose of an injected proxy anyway. Not to mention closing it in one thread will cause a potential fault in another thread. Again note that I dislike the idea of shared proxies.
Another argument is that I am planning to inject the same instance for each session in this environment, so Open & Close for each service call shouldn't matter ?
Yes, like I said if you are going to inject then you should not call open/close. Then again you should not share in a multi-threaded environment.
So which approach should I take
Follow these guidelines
Singleton? PerCall? PerSession? That entirely depends on the nature of your service. Does it share state between method calls? Make it PerSession otherwise you could use PerCall. Don't want to create a new service instance more than once and you want to optionally share globals/singletons between method calls? Make it a Singleton
Rather than inject a shared concrete instance of the WCF client proxy, instead inject a mechanism (a factory) that when called allows each recipient to create their own WCF client proxy when required.
Do not call open/close after each call, that will hurt performance regardless of service instance mode. Even if your service is essentially compute only, repeated open/close for each method call on a Singleton service is still slow due to the start-up costs of the client proxy
Dispose the client proxy ASAP when no longer required. PerSession service instances remain on the server eating up valuable resources throughout the lifetime of the client proxy or until timeout (whichever occurs sooner).
If your service is localmachine, then you consider the NetNamedPipeBinding for it runs in Kernel mode; does not use the Network Redirector and is faster than TCP. Later when you deploy a remote service, add the TCP binding
I recommend this awesome WCF tome

Failover mechanisum for WCF services serving enterprise application

We have set of WCF services running on single computer which collectively serves an WPF application which could be on same machine or on remote machine (within same network only). We need failover mechanisum so whenver any of the service crashes or hangs - we want to restart the service and initialize it by calling appropriate method.
Since we are not aware of what is the industry standard for implementing failover for WCF service - we have implemented like this way. We start main WCF service hosted in console app along with one more secondary WCF service which constantly checks health of main WCF service by calling exposed method on given endpoint. If main WCF service fails, it takes role of main WCF service and launches another secondary WCF service.
The above approach is working fine but only problem we have seen is memory since we launch services in pair and every host requires 10MB of memory.
Can anyone help me what is the industry practice for implementing failover for this kind of scenario?

How to make WCF Service with a background worker thread?

I have a WCF service that all clients connect to in order to get notifications \ reminders (using a CALLBACK interface they implement). Currently the WCF service is self-hosted, but the plan is to have it hosted in a Windows Service.
The WCF service has a 'Publish', 'Subscribe' and 'Unsubscribe' operations.
I need to have a background worker thread of some sort poll an SQL server database table constantly [every XXX minutes], and look for certain 'reminder' rows. Once it finds them - it should notify all the connected clients.
I thought of 2 ways of achieving this.
.
METHOD A :
Have a separate EXE project (don't want it to be a console, so what should it be - a Windows Service ?) that will start and run a background thread. The background thread will connect to the 'Reminder' service as one of its clients. The background thread will poll the database, and once it finds something - it will send a 'Publish' message to the WCF service, that will make the WCF service send the reminder to all the subscribed clients.
.
METHOD B :
Somehow make the background thread run within the WCF service project, and when it detects a new reminder row in the database, somehow make it 'signal' the WCF service with the info, and the WCF service will then send this info to all subscribed clients.
.
Which method is better ? Any other suggestions ?
If this is a long running process, a windows service is the perfect solution.
Your main Win Service thread will be polling the DB, queuing the results into some kind of supplier/consumer thread safe collection.
You can host a WCF service within the win service, which can then consume (remove) any results from the queue and pass them back to the client as requested (calls into the WCF will come in on their own thread)
This is a pretty common architecture, and not difficult to implement.
Method A:
If you were to create two separate hosts (i.e. one for the WCF service and one for the "Polling" service) then you really have only one option to make it all work nicely.
Windows Service communication is very limited (without the help of a service endpoint, e.g. WCF). Therefor, if you were to host your "Polling" service in a Windows Service, you must couple it with a WCF service anyway.
It is then feasible to host both services together in one Windows Service and by manually instantiating the WCF host and passing into the constructor a "Polling" service.
protected override void OnStart(string[] args)
{
//...
// This would be you "polling" service that would start a background thread to poll the db.
var notificationHost = new PollingService();
// This is your WCF service which you will be "self hosted".
var serviceHost = new WcfService(notificationHost);
new ServiceHost(serviceHost).Open();
//...
}
This is far from ideal because you need to communicate via events between the two services, plus your WCF service must run on singleton mode for manual instantiation to work... So this leaves you with...
Method B:
If you were to host the "Polling" services inside your WCF service, you are going to run into a number of issues.
You need to be aware of the number of instances of the "Polling" services that gets created. If your WCF service has been configured to be instantiated for every session, you could end up with too many "Polling" services and that may end up killing your db/servers.
To avoid the first issue, you may need to set a singleton WCF service, which may lead to a scaling issue in the near future where one WCF service instance is not enough to handle the number of connection requests.
Method C:
Given the drawbacks in Method A and B, the best solution would be to host two independent WCF services.
This is your regular service where you have subscriber/unsubscribe/publish.
This is your polling singleton service with subscribe/unsubscribe.
The idea is that your regular service, upon receiving a subscriber will open a new connection to your polling service or use an existing one (depending on how you configure your session) and wait for a reply. Your polling service is a long running WCF service that polls your db and publish the notification to its subscribers (i.e. the other WCF host).
Pros:
You are assured that there will be only one polling service.
You could scale your solution to host the regular service in IIS and the polling service in Windows Service.
Communication limitations is minimal between the two services and no need for events.
Test each service interdependently through their interfaces.
Low coupling and high cohesion between the services (this is what we want!).
Cons:
More services means more interfaces and contracts to maintain.
Higher complexity.

Is WCF Duplex a good choice?

After developing mini project with WCF duplex (Chat Service | Sms Service), I got a Point that maybe not be correct!!
I believed Duplex theory is good and useful but there is a lot problem about using Wcf Duplex. (like reliable session, Time-out exceptions, Client address-Management on server side, proxy management on Client Side)
am I think wrong ? am I miss something?
For more Information I Used wsDualHttpBinding not tcpBinding.
If you need bidirectional communication and you want to use WCF, duplex channels are the way to go. You just need to design your application correctly and correctly handle all problems you have described. If you feel that these problems are overhead and make things even worse you can always use network programming directly (sockets) or handle bidirectional communication by yourselves exposing separate service on server and another on client (where first call from client inform server about clients address) - this scenario will suffer from the same communication problems as WsDualHttpBinding.
WsDualHttpBinding itself is special kind of duplex communication. I personally don't like it because people very often misuse it. The problem is that this binding uses two separate connections - one from client to server and second from server to client. That is big difference to net.tcp where only connection initiated from client to server is used. Obviously using WsDualHttpBinding over internet (= you don't have control over client machines) becomes much more complicated because each client must configure its firewall (in computer, on home internet gateway, etc.) to allow connection on some port. Also if you want to run more then one instance of application on the same client machine, each instance must use its own port.

Server architecture question. (WCF+NServiceBus)

First of all i will describe current state:
Server consists of several WCF services, hosted in one or several win services on diffirent machines.
Service responsible for recieving data from diffirent devices. Communication with devices is implemented using sockets. Service instance mode - singleton.
Data broker service - responsible for persisting data and sharing in by request. Instance mode - singleton.
Configuration service - responsible for changing configuration database and working with administration console(WPF app, like SSMS). Handles connections from console, subscriber management, etc. Instance mode - singleton.
Client access service - quite the same as above thith management of clients but also notifyes clients of new data, and acts like facade to service bus. And singleton again.
Identity management service - Checks permissions and returns result. Singleton.
All of those services are connected with NServiceBus and i realy like how it works at this moment.
But:
Too many singletons. Mainly because to use servicebus i must have single instance of it afaik. I dunno maybe i can use nservice bus in session mode, but dont know how to handle issue that all of those services will use one queue.
And what if i will have 300+ clients? singleton can become unresponsive..
And i wanted to ask for some critics about all of this and maybe some one could suggest something.
Thanks in advance.
Alexey
Alexey,
While you should only have one instance of the bus per process, you can put that instance in a globally accessible place (as shown in the AsyncPages sample), and use that from non-singleton objects like web pages and WCF services.
Also, it is probably not appropriate to have all your services using one queue. Without better understanding your situation, I'd give the default recommendation of one queue for each of the services you identified.
Hope that helps.