c# - 对服务类使用静态只读引用有什么问题吗?

标签 c# asp.net oop soa

我继承了这段代码,原作者不知为何非常喜欢static readonly references。

我在下面概述了一般模式,拥有这些静态只读引用会产生什么后果?

public class DbAccess
{
    private static readonly ISomethingFactory = SomethingFactories.GetFactory("1");
    private static IThing1Dao Thing1Dao { get {return ISomethingFactory.Thing1Dao; }}
    private static IThing2Dao Thing2Dao { get {return ISomethingFactory.Thing2Dao; }}
}

public class SomethingFactories
{
   public static ISomethingFactory GetFactory(string key) 
   {
      switch(key)
      {
         case "...":
         return new SomeFactory();
      }
   }
}    

public class SomeFactory : ISomeFactory
{    
    public IThing1Dao Thing1Dao
    {
       get { return new Thing1Dao(); }
    }
}    

public class SomeService : ISomeService
{
    private static readonly IThing1Dao thing1Dao = DbAccess.Thing1Dao
    private static readonly IThing2Dao thing2Dao = DbAccess.Thing2Dao

    public Thing1Object1 GetObject1(int id)
    {
        return thing1Dao.GetObject1(id);    
    }

    public Thing1Object2 GetObject2(int id)
    {
        return thing1Dao.GetObject2(id);
    }
}

.aspx 页面中的用法如下:

public class MyBasePage : System.Web.UI.Page
{
    protected static readonly SomeService someService = new SomeService();     
}    

public class SomeAspxPage : MyBasePage
{
   void btnAddObject1(...)
   {
      Thing1Object1 obj1 = someService.GetObject(1);
   }
}

最佳答案

static 表示只有一个 ISomethingFactory 实例存在,并且可以通过该类型访问该实例(不是每个 DbAccess 实例一个实例) >).

readonly 表示初始化后,该值不能被覆盖。

这是基于启动时数据(例如来自 app.config 的数据)执行初始化的相当正常的模式。

关于c# - 对服务类使用静态只读引用有什么问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15123711/

相关文章:

jquery - 如何编写 jQuery 来禁用从单选按钮列表中选择项目时的下拉菜单

c# - 为什么 CSS 文件会受到全局 asax 中 Application_BeginRequest 的影响

c++ - 将对象作为参数传递,而不是传递对象的变量

c# - 覆盖显式接口(interface)实现?

php - 避免在每个函数中调用数据库类

动态创建的文本框上的 C# 线程安全文本更新

c# - 该字段必须是数字

c# - 使用简单方法安全删除文件?

asp.net - Dapper.net交易问题

c# - 正则表达式 : replace a string