How do I Instantiate component as Singleton at registration?

时光总嘲笑我的痴心妄想 提交于 2019-12-01 02:22:28

问题


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!

I have the following:

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

Now quite rightly this is being lazy-loaded, i.e. the lambda expression passed in to UsingFactoryMethod() isn't being executed until I actually ask Castle to Resolve me the instance of the class.

But I would like Castle to create the instance as soon as I have registered it. Is this possible?


回答1:


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




回答2:


For this simple case you could just register an existing instance:

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



回答3:


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:

    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();


来源:https://stackoverflow.com/questions/7108062/how-do-i-instantiate-component-as-singleton-at-registration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!