简体   繁体   English

如何在注册时将组件实例化为单例?

[英]How do I Instantiate component as Singleton at registration?

I can imagine this might be quite straight forward to do in Castle but I'm new to the technology and have been Googling for hours with no luck!我可以想象这在 Castle 中可能很简单,但我是这项技术的新手,并且已经在谷歌上搜索了几个小时但没有运气!

I have the following:我有以下几点:

container.Register(
Component.For<MySpecialClass>().UsingFactoryMethod(
    () => new MySpecialClass()).LifeStyle.Singleton);

Now quite rightly this is being lazy-loaded, ie the lambda expression passed in to UsingFactoryMethod() isn't being executed until I actually ask Castle to Resolve me the instance of the class.现在完全正确的是,这是延迟加载的,即传递给 UsingFactoryMethod() 的 lambda 表达式在我实际要求 Castle 解析我类的实例之前不会执行。

But I would like Castle to create the instance as soon as I have registered it.但是我希望 Castle 在注册后立即创建实例。 Is this possible?这可能吗?

For this simple case you could just register an existing instance :对于这个简单的情况,您可以只注册一个现有实例

var special = new MySpecialClass();
container.Register(Component.For<MySpecialClass>().Instance(special));

You can just use the built it Startable facility like so:您可以像这样使用内置的可启动工具:

container.AddFacility<StartableFacility>();
container.Register(Component.For<MySpecialClass>().LifeStyle.Singleton.Start());

You can read about it here你可以在这里阅读

The answer re using "Instance" may not always be feasible (if the class has layers of dependencies itself, it won't be easy to new it up).重新使用“实例”的答案可能并不总是可行(如果类本身具有依赖层,则不容易对其进行更新)。 In that case, at least in Windsor 2.5, you could use this:在这种情况下,至少在 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM