6

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?

0

3 Answers 3

12

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

var special = new MySpecialClass();
container.Register(Component.For<MySpecialClass>().Instance(special));
4
  • Thank you! Here's what I ended up using - container.Register(Component.For<MySpecialClass>().Instance(new MySpecialClass()));
    – jameskind
    Aug 19, 2011 at 10:56
  • 1
    This does not look like the best approach since you are not leaving the instantiation to the container, and hence breaking the IoC pattern. Nov 20, 2013 at 16:26
  • @DavidPerlman Right, back when I wrote this answer, I think there wasn't such an easy way as the recent answer by MosheLevi describes. Dec 16, 2013 at 22:02
  • I find this a lot cleaner than the accepted answer. In my mind it shouldn't be about blindly following patterns. This makes it a lot easier for the next developer to figure out what's going on. And the instantiation and registration is still in one place.
    – Tobias
    May 24, 2017 at 18:06
11

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

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.