C# 如何在注册时将组件实例化为Singleton?
我可以想象,在Castle中这样做可能很简单,但我对这项技术还不熟悉,已经在Google上搜索了好几个小时,运气不好 我有以下资料:C# 如何在注册时将组件实例化为Singleton?,c#,castle-windsor,C#,Castle Windsor,我可以想象,在Castle中这样做可能很简单,但我对这项技术还不熟悉,已经在Google上搜索了好几个小时,运气不好 我有以下资料: container.Register( Component.For<MySpecialClass>().UsingFactoryMethod( () => new MySpecialClass()).LifeStyle.Singleton); container.Register( Component.For()。使用FactoryMe
container.Register(
Component.For<MySpecialClass>().UsingFactoryMethod(
() => new MySpecialClass()).LifeStyle.Singleton);
container.Register(
Component.For()。使用FactoryMethod(
()=>新MySpecialClass()).LifeStyle.Singleton);
现在非常正确地说,这是延迟加载的,也就是说,传入UsingFactoryMethod()的lambda表达式在我实际请求Castle解析类的实例之前不会被执行
但我希望Castle在注册后尽快创建该实例。这可能吗?对于这个简单的案例,您可以:
var special=new MySpecialClass();
Register(Component.For().Instance(special));
重新使用“实例”的答案可能并不总是可行的(如果类本身有依赖层,那么重新创建它并不容易)。
在这种情况下,至少在Windsor 2.5中,您可以使用:
public static void ForceCreationOfSingletons(this IWindsorContainer container)
{
var singletons =
container.Kernel.GetAssignableHandlers(typeof (object))
.Where(h => h.ComponentModel.LifestyleType == LifestyleType.Singleton);
foreach (var handler in singletons)
{
container.Resolve(handler.ComponentModel.Service);
}
}
// usage container.ForceCreationOfSingletons();
您只需使用内置的可启动设备,如下所示:
container.AddFacility<StartableFacility>();
container.Register(Component.For<MySpecialClass>().LifeStyle.Singleton.Start());
container.AddFacility();
container.Register(Component.For().lifety.Singleton.Start());
你可以读一下谢谢!下面是我最后使用的-container.Register(Component.For().Instance(newmyspecialclass());这看起来不是最好的方法,因为您没有将实例化留给容器,因此打破了IoC模式。@DavidPerlman对,当我写这个答案时,我认为没有像MosheLevi最近的答案所描述的那样简单的方法。我发现这比公认的答案干净得多。在我看来,这不应该是盲目地遵循模式。这使得下一个开发人员更容易弄清楚发生了什么。实例化和注册仍然在一个地方。
container.AddFacility<StartableFacility>();
container.Register(Component.For<MySpecialClass>().LifeStyle.Singleton.Start());