Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top