c# - ICodeCompiler, dynamic code and statics
I have a system that compiles and executes c# code "on the fly", so to speak. Static classes are used holding conf开发者_如何转开发ig data within the system.
If I access a static class from within the "on the fly compiled code" - all OK.
However, If I access a static class from within the "on the fly compiled code" then try to access the same static class outside of the "on the fly compiled code", all config data in the static class has been lost. Almost like it has been reinstanciated.
The "on the fly compiled code" is run in the same app domain, if this makes a difference.
Can anyone explain why this occurs? (Accessing a static from within the compiled code resets its config data)
Best,
Benny
static in C# is not the same as static in C code.
I think you want a singleton.
public sealed class Clazz
{
private readonly static Clazz _instance = new Clazz();
public static Clazz Instance { get { return _instance; } }
static Clazz { /* Required for lazy init */ }
private Clazz()
{
// implementation here
}
}
It guarantees that there is one instance of the class, ever, in an AppDomain.
If you are loading your dynamically-compiled code in a distinct AppDomain, and you want a cross-appdomain singleton, there are solutions for that too (Google is your friend).
精彩评论