How to activate a component as Singleton during registration?

I can imagine that it can be quite straightforward in the castle, but I am new to this technology and have not been working in Googling for a long time!

I have the following:

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

Now it’s absolutely true that this is lazily loading, i.e. the lambda expression passed to UseFactoryMethod () is not executed until I ask Castle to allow me an instance of the class.

But I would like Castle to instantiate as soon as I registered it. Is it possible?

+6
source share
3 answers

You can simply use the built-in Startable object as follows:

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

You can read about it here.

+9
source

In this simple case, you can simply register an existing instance :

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

The re answer using Instance may not always be feasible (if the class has dependency layers, it will not be easy to update it). In this case, at least in Windsor 2.5, you can 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(); 
+1
source

Source: https://habr.com/ru/post/895326/


All Articles