views:

28

answers:

1

Is it possible to perform some custom processing when Windsor instantiates a type?

Something similar to:

        container.Register(
                  AllTypes.Pick()
                      .FromAssembly(Assembly.GetExecutingAssembly())
                      .BasedOn<MyMarkerInterface>()
                      .WhenInstantiating(instance => // do some stuff with this instance)
                      .Configure(component => component.Startable().LifeStyle.Singleton)
                      .WithService.Base());

Currently we are using IStartable. Since the "Start" code (i.e. the custom processing) is identical it would be nice to move this logic out of each class.

Thanks! Brian

+4  A: 

You mean something like OnCreate method?

    container.Register(
              AllTypes.FromAssembly(Assembly.GetExecutingAssembly())
                  .BasedOn<MyMarkerInterface>()
                  .WithService.Base()
                  .OnCreate((kernel, instance) => instance.CreatedAt = DateTime.Now)
);

Singleton is default lifestyle so you don't have to state that explicitly.

Notice however that behavior is slightly different here, as compared to how Startable facility works.

  • when component is startable it gets instantiated and started by the container itself, as soon as possible (when all its required dependencies become available).
  • OnCreate is called before your component is returned from the container but it does not create it proactively. So if you never pull this component, its OnCreate will not be called.

Also while the docs state that OnCreate lives in a facility, it is not true anymore (yeah, we need to update docs). This method will work out of the box.

Krzysztof Koźmic
+1, but the container-agnostic solution is a Decorator :)
Mark Seemann
I'm not sure about the decorator. Where would you put the logic? In .ctor? What if you want to have it executed once your component is fully instantiated, ie with properties wired up as well?Call it lazily upon first call to any method? Not sure it's such a great idea.
Krzysztof Koźmic
Thanks Krysztof. For other readers, the OnCreate method was added in release 2.1.0.
Brian

related questions