Static instance of DataContractJsonSerializer - good or bad design?
I have a class which I am using to serialize and deserialize business objects in an ASP.NET application.
The class contains this static variable:
private static DataContra开发者_如何学JAVActJsonSerializer m_serializer = new DataContractJsonSerializer(typeof(MyBusinessObject));
... and two static methods in the class:
public static string SerializeJson(MyBusinessObject bo);
public static MyBusinessObject DeserializeJson(string json);
In these methods, I use the static DataContractJsonSerializer object (m_serializer) to perform serialization and deserialization. This way, I do not need to instantiate a DataContractJsonSerializer instance for each call.
Is it correct design to use a static variable in this way?
Could I run into any problems if I get lots of hits on the serialize/deserialize code?
It will be called from website which gets 100s of concurrent hits every second.
As Alex mentioned, you can run into problems - the documentation of the class states that it's not thread safe (at least not the methods used to read / write objects). By doing a quick look on reflector it seems like the serialization can actually work (assuming you're not serializing the same object at the same time in different threads, that's a whole new can of worms), but since it's an internal implementation detail, it's possible that in a new version of the framework the class has some change (i.e., optimization) and that won't be true anymore.
An option which you can consider is to have a pool of serializers which can be reused. Your code would take one serializer from the pool, use it to serialize / deserialize, and then return it to the pool. This way you get the benefit of reusing the instances, but without the risk of using a thread-unsafe class in multiple threads.
Finally, have you verified that the creation of the serializers is indeed a problem (i.e., by profiling)? It's possible that the time it takes is negligible in your scenario, and using some sort of reuse would just add unnecessary complication to your code.
精彩评论