在 Unity 中使用延迟实例化的 RegisterInstance

RegisterInstance with deferred instantiation in Unity

我在 .NET 中有一个(相当标准的)单例对象(它具有受保护的构造函数和 Instance 属性)。

我需要在Unity容器中注册它的实例,所以调用

container.RegisterInstance<IFoo>(FooSingleton.Instance);

但是我想避免它在容器注册方法中的实例化(推迟它只在需要时调用)因为有可能不需要它并且它的初始化是扩展的。

有什么办法可以实现吗?

您可以使用 InjectionFactory 按需创建您的实例,并使用 ContainerControlledLifetimeManager 使其成为单例:

container.RegisterType<IFoo, FooSingleton>(new ContainerControlledLifetimeManager(), 
    new InjectionFactory(c => FooSingleton.Instance));