Is it possible to scope ServiceStack.Text.JsConfig

2019-06-20 07:58发布

问题:

I'm writing a custom library that uses ServiceStack.Text internally. Other libraries that consume mine may also use ServiceStack.Text.

I want to change some JsConfig options (specifically date handling), but, like any good citizen, I don't want my modifications of those values to cause side effects for my consumer.

Unfortunately JsConfig is a static class, so its settings are static, and would bleed to other consumers of ServiceStack in the same AppDomain I believe. That's an undesired behavior.

Is there some way to scope my configuration changes to just my calls to the JsonSerializer?

Update

I do realize there is the JsConfig.Reset method, unfortunately if the caller has customized it already, that would be lost.

I could save values and restore them, but I would have to synchronize access to the serializer, which also kind of defeats the purpose.

Hopefully there is something simple I'm missing?

回答1:

This functionality was missing in ServiceStack.Text so I added a pull request for it.

Basically now if you wanted to scope your config settings you can use the following syntax:

using(var config = JsConfig.With(new Config { DateHandler = ... }))
{
}

And the values will no longer be set once the using block goes out of scope, its ThreadStatic as well so won't affect other threads.



回答2:

One possibility I've though of is just using a custom type internal to my library as the root object to serialize, and then specifying the JsConfig values specifically for that.

internal class MyInternalObject { }

JsConfig<MyInternalObject>.DateHandler = ...

I'm not sure if the root configuration values propagate down to child objects in the serialization, but easy enough to test.