实现Singleton模式时出错(在相互递归的类型中)

时间:2011-03-24 19:43:44

标签: f# singleton lazy-evaluation

我正在尝试实现单例模式,但收到错误。我的实现在功能上与this answerthis one完全相同。我正在使用类而不是模块,因为它实现了一个接口。

type SystemObjectFactory private () =
    static let instance = lazy ( SystemObjectFactory() )
    static member Instance = instance.Value //ERROR

例外是:

  
    

System.InvalidOperationException:文件或类型的静态初始化导致静态数据在完全初始化之前被递归访问。

  

我该如何纠正?

作为旁注,我不确定为什么以下(我更喜欢)也不起作用:

type SystemObjectFactory private () =
    static let instance = SystemObjectFactory()
    static member Instance = instance

更新

我可能已经发现了这个问题。该类是从相互递归类型的静态构造函数引用的。显然,这是.NET中的黑暗和禁止的魔法。

更多背景信息:

type Entity() =
    static do
        Bootstrapper(SystemObjectFactory.Instance).Init() //PURE EVIL

and SystemObjectFactory private () =
    static let instance = SystemObjectFactory()
    static member Instance = instance

1 个答案:

答案 0 :(得分:2)

您的首选版本以何种方式无效?当我输入FSI时它似乎有效:

> type SystemObjectFactory private () =
    static let instance = SystemObjectFactory()
    static member Instance = instance;;

type SystemObjectFactory =
  class
    private new : unit -> SystemObjectFactory
    static member Instance : SystemObjectFactory
  end

> SystemObjectFactory.Instance;;
val it : SystemObjectFactory = FSI_0002+SystemObjectFactory

<强>更新

尝试切换递归类型的顺序!

type SystemObjectFactory private () =
    static let instance = SystemObjectFactory()
    static member Instance = instance
and Entity() =
    static do
        SystemObjectFactory.Instance = SystemObjectFactory.Instance |> ignore //slightly evil