Error implementing Singleton pattern (within mutually recursive types)
I'm attempting to implement the singleton pattern, but receiving an error. My implementation looks functionally identical to this answer and this one. I'm using a class instead of a module because it implements an interface.
type SystemObjectFactory private () =
static let instance = lazy ( SystemObjectFactory() )
static member Instance = instance.Value //ERROR
The exception is:
System.InvalidOperationException: The static initialization of a file or type resulted in static data being accessed recursively before it was fully ini开发者_如何学Gotialized.
How can I correct this?
As a side note, I'm not sure why the following (which I prefer) doesn't work either:
type SystemObjectFactory private () =
static let instance = SystemObjectFactory()
static member Instance = instance
UPDATE
I may have discovered the problem. This class is being referred to from the static constructor of a mutually recursive type. Apparently, this is dark and forbidden magic in .NET.
More context:
type Entity() =
static do
Bootstrapper(SystemObjectFactory.Instance).Init() //PURE EVIL
and SystemObjectFactory private () =
static let instance = SystemObjectFactory()
static member Instance = instance
In what way does your prefered version not work? When I type it into FSI it seems to work:
> 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
Update
Try switching the order of your recursive types!
type SystemObjectFactory private () =
static let instance = SystemObjectFactory()
static member Instance = instance
and Entity() =
static do
SystemObjectFactory.Instance = SystemObjectFactory.Instance |> ignore //slightly evil
精彩评论