区分引用静态属性的两个调用程序集的最佳方法

时间:2015-02-20 13:05:31

标签: c# .net

汇编" 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];
  }
}

2 个答案:

答案 0 :(得分:5)

不要使用静态属性:

class ValuableClass
{
    public string MyProperty { get; set; }
}

现在,BC都可以创建ValuableClass的单独实例


现在,我们如何让所有B和C都能访问这些实例? “干净”的方式是在整个B和C中使用依赖注入,但这对于大型遗留项目来说可能是不可行的。

作为一个简单的解决方案,BC可以通过静态属性提供 ValuableClass的实例

class SomeClassInB
{
     private static readonly ValuableClass myValuableStuff = new ValuableClass();
     public static ValuableClass MyValuableStuff { get { return myValuableStuff; } }
}

// same for C

由于SomeClassInBSomeClassInC只能分别在BC中访问,因此不存在一个程序集“污染”另一个数据的风险。

答案 1 :(得分:1)

在可以在调用setter之前调用getter的情况下,依赖于调用程序集的FullName是一种相当脆弱的方法,因为你的代码开始依赖于识别程序集的“魔术常量” BC。如果你在获得之前需要一套,你的方法就可以了。我会更进一步,并使用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)的方法替换该属性。这样,程序集BC可以预先创建自己的标识符,并根据需要使用它们来获取和设置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;
}