简体   繁体   中英

Keep dictionary in memory in a WCF service

I have a WCF service that uses a dictionary for several service parameters. This dictionary is created by parsing an XML file saved on a local disk. In order to allow updating of the file, I want to use a FileSystemWatcher in order to recreate the dictionary if the file is chnaged.

I use this mechanism for other things, and I wanted to use it in the service as well. My problem is that, from my understanding, WCF creates an instance of the service class per-request (I know this is configurable, but we use per-request), and I want to hold the dictionary in a place where it will remain in memory after the instance completes servicing the request.

Can this be done and where will be the best place to put the logic for the parsing of the XML file and the storing of the dictionary?

You can create custom configuration sections to store your XML stuff in Web.config file using ConfigurationSection and you can simply read from the config file. The config values are cached for you by the framework. Also you don't need a file watcher with this approach. If you "touch" Web.config, application is automatically restarted for you and new values are read into the cache.

You can store your dictionary in a static member and initialize it in the static constructor or lazyly.

If your service is hosted in iis, keep in mind, iis will handle the lifecycle of the host process which probably means your dictionary will be reloaded when the app domain is recreated.

Firstly I assume you are using the Dictionary Class, according to msdn: A Dictionary can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with write accesses, the collection must be locked during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

For a thread-safe alternative, see ConcurrentDictionary.

Secondly, you may construct a singleton class to wrap the Dictionary, so only one instance of the dictionary will be instantiated for an app domain which handle multiple requests. There are many ways to construct singleton, and which implementation to choose depend on your usage patterns, please google C# and singleton to choose one from many alternatives.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM