How to globally add data to a static class in another dll
In project A, i have a static class which stores data for specific types, this data is initialized in the static constructor
public static class MyStaticClass
{
private static readonly Dictionary<Type, object> data = new Dictionary<Type, object>();
static MyStaticClass() { /*fill data here*/ }
public static object GetData(Type type) { return data[type]; }
public static void SetData(Type type, object o) { data[type] = o; }
}
Project B uses project A. Project B is also a library. In project B i want to use this class not only for types added in the static constructor, but also for types defined in B and its dependencies.
Basically somewhere in B i want to have the following code:
MyStaticClass.SetData(typeof(TypeInB), new object());
MyStaticClass.SetData(typeof(TypeInDllUsedByB), new object());
What would be the appropriate place to put this code in project B?
I project B there are several places i'd开发者_StackOverflow like to call GetData
without having to worry if previous code has already been executed.
I thought about placing it in static TypeInB()
and any other classes i'd like to use, but that won't work for classes defined in other assemblies.
Create wrapper class in project B that will fwd calls to repository in project A. For example,
public static class MyStaticClassInB
{
static MyStaticClassInB() { /*fill data here*/ }
public static object GetData(Type type) { return MyStaticClass.GetData(type); }
public static void SetData(Type type, object o) { MyStaticClass.SetData(type, o); }
}
Always use MyStaticClassInB in Project B (and not MyStaticClass). Now correct location to initialize types from B would be static constructor of this class.
精彩评论