What are the solutions for data persistance in a .NET webservice?
I have a webservice. I give an id to my webservice and this one return the correct objet.
WCF has built in instance management.
You could use a static collection:
private static List<MyObject> list = new List<MyObjec>();
and of course since this is a multithreaded application where potentially you could have concurrent access to this collection, you must ensure to synchronize the access to it. Or if you are using .NET 4.0 simply use a thread safe ConcurrentBag<T>
:
private static ConcurrentBag<MyObject> list = new ConcurrentBag<MyObjec>();
Of course you should perfectly fine be aware that by using an in-memory structure to store your data your data life is basically tied to the life of the web application. And since IIS could recycle the application domain at any moment (a certain period of inactivity, certain CPU/memory thresholds are reached) everything you have stored into memory goes into the void.
By the way if you go that route, be prepared this to happen very often, every time you recompile your web service, because by recompiling you are basically modifying the assemblies in the bin folder and the web server will simply recycle the application.
So yeah, all this wall of text to tell you to persist your data somewhere else than in-memory :-) You've got so many possibilities ranging from files in different formats, databases, embedded databases, ...
Alternatively, you can make your service a singleton
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,
ConcurrencyMode = ConcurrencyMode.Single)]
class Service
...
However, this approach leads to huge problems in future. Do not store anything in-memory. If you do, you embed a state into the application. This leads to tremendous amount of work needed to achieve high reliability and scalability. No state, no pain.