汇编" A"提供有价值的类,提供静态属性...
class ValuableClass
{
public static string MyProperty { get; set; }
}
大会" B"和" C"使用ValuableClass及其静态属性。在" B"和" C"在同一个过程中加载。
我应该如何重构MyStaticProperty实现以保持" B"和" C"电话被隔离?我不能依赖线程ID(多个线程可能会为每个程序集更改静态属性)而且我也不能依赖进程ID,因为它是相同的进程。
我想简化代码应如下所示,但我不确定它是最佳做法
protected static IDictionary<string, string> MyProperties
public static string MyProperty
{
set {
string key = Assembly.GetCallingAssembly().FullName
MyProperties[key] = value;
}
get {
string key = Assembly.GetCallingAssembly().FullName
return MyProperties[key];
}
}
答案 0 :(得分:5)
不要使用静态属性:
class ValuableClass
{
public string MyProperty { get; set; }
}
现在,B
和C
都可以创建ValuableClass
的单独实例。
现在,我们如何让所有B和C都能访问这些实例? “干净”的方式是在整个B和C中使用依赖注入,但这对于大型遗留项目来说可能是不可行的。
作为一个简单的解决方案,B
和C
可以通过静态属性提供 ValuableClass
的实例:
class SomeClassInB
{
private static readonly ValuableClass myValuableStuff = new ValuableClass();
public static ValuableClass MyValuableStuff { get { return myValuableStuff; } }
}
// same for C
由于SomeClassInB
和SomeClassInC
只能分别在B
和C
中访问,因此不存在一个程序集“污染”另一个数据的风险。
答案 1 :(得分:1)
在可以在调用setter之前调用getter的情况下,依赖于调用程序集的FullName
是一种相当脆弱的方法,因为你的代码开始依赖于识别程序集的“魔术常量” B
和C
。如果你在获得之前需要一套,你的方法就可以了。我会更进一步,并使用Assembly
本身作为词典的关键词:
protected static IDictionary<Assembly,string> MyProperties =
new Dictionary<Assembly,string>();
public static string MyProperty {
set {
MyProperties[Assembly.GetCallingAssembly()] = value;
}
get {
return MyProperties[Assembly.GetCallingAssembly()];
}
}
如果您想要一个更受控制的解决方案,请使用带有标识符(例如GUID)的方法替换该属性。这样,程序集B
和C
可以预先创建自己的标识符,并根据需要使用它们来获取和设置MyProperty
:
protected static IDictionary<Guid,string> MyProperties =
new Dictionary<Guid,string>();
public static string GetMyProperty(Guid id) {
return MyProperties[id];
}
public static void SetMyProperty(Guild id, string val) {
MyProperties[id] = val;
}