Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persist object in C# .NET Web Service

Am stuck on what am sure is a fundamental and easy to solve problem in WCF, just need to be guided towards the right way.

I have a large object (which is actually a trained text classifier) that I need to expose through a Web Service in C# .NET. The classifier object can be loaded from disk when the service initially starts, but I don't want to keep loading it from disk for every request (the object that services requests currently occupies about 6 GB in memory, and it takes a while to keep loading it from disk for every request), so instead I want to persist that object in memory throughout all requests to that web service, and the object should only be loaded when the service starts (instead of loading it when the first web request triggers it).

How would I go about doing that?

Thanks for any help!

like image 700
ToOsIK Avatar asked Oct 04 '12 09:10

ToOsIK


2 Answers

Probably the easiest way is to create your service as a singleton. This involves specifying InstanceContextMode = InstanceContextMode.Single in a ServiceBehavior attribute on your service class definition.

However it is very questionable if sending a 6GB object over the wire using WCF is advisable. You can run into all sorts of service availability issues with this approach.

Additionally, singletons are not scalable within a host (can be only one instance per host), although you can host multiple singleton services and then load-balance the requests.

like image 177
tom redfern Avatar answered Sep 19 '22 02:09

tom redfern


The way I've done this in projects that I've had the problem with in the past is to self host the WCF service inside a Windows Service.

I've then set the data storage object up inside the service as a singleton that persists for the life of the service. Each WCF service call then gets the singleton each time it needs to do something with the data.

I would avoid running in IIS simply because you don't have direct control of the service's lifetime and therefore don't have enough control of when things are disposed and instantiated.

like image 38
Richard Comish Avatar answered Sep 20 '22 02:09

Richard Comish