2

I have a large number of classes depending on a watchdog component. I add a reference to the depending class to the watchdog instance.

Currently I use the following code to accomplish this.

   class MyClass {
      public MyClass(IWatchDog watchDog) {
        watchDog.WatchingType = typeof(MyClass);
      }
   }

My installer:

class IoC: IWindsorInstaller {
    public void Install(IWindsorContainer container, IConfigurationStore store) {
        container.Register(Component.For<MyClass>());
        container.Register(Component.For<IWatchDog>().ImplementedBy<WatchDogService>());
    }
}

Is it possible to let the installer do this assignment for me? Here's what I have in mind in pseudo-code, OnResolving being my imaginary method:

class IoC : IWindsorInstaller {
    public void Install(IWindsorContainer container, IConfigurationStore store) {
        container.Register(Component.For<MyClass>());
        container.Register(
            Component.For<IWatchDog>()
                .ImplementedBy<WatchDogService>()
                .OnResolving<IWatchDog>(
                    new Action((Type typeBeingResolved, IWatchDog instance) =>
                        instance.WatchingType = typeBeingResolved));

    }
}

So in this case I imagine typeBeingResolved would equal to typeof(MyClass) if container.Resolve<MyClass>() is called, or null if someone calls container.Resolve<IWatchDog>().

Obviously, if I could somehow have access to the instance of the type being resolved a bit like in OnCreate() that would work as well.

1 Answer 1

4

Using a custom facility you can change your default activator for your components to be an activator that does what you want. Here's a working solution:

using Castle.Core;
using Castle.MicroKernel;
using Castle.MicroKernel.ComponentActivator;
using Castle.MicroKernel.Context;
using Castle.MicroKernel.Facilities;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; 

namespace ComponentCreater
{
public interface IWatchDogService
{
    Type WatchingType { get; set; }
}

public class WatchDogService : IWatchDogService
{
    public Type WatchingType { get; set; }
}


public class WatchedClassViaConstructor
{
    private readonly IWatchDogService watchDogService;

    public WatchedClassViaConstructor(IWatchDogService watchDogService)
    {
        this.watchDogService = watchDogService;
    }

    public void Print()
    {
        Console.WriteLine(this.watchDogService.WatchingType.Name);
    }
}

public class WatchDogFacility : AbstractFacility
{
    protected override void Init()
    {
        this.Kernel.ComponentModelCreated += Kernel_ComponentModelCreated;
    }

    private void Kernel_ComponentModelCreated(ComponentModel model)
    {
        model.CustomComponentActivator = typeof(WatchedComponentActivator);   
    }
}

public class WatchedComponentActivator : DefaultComponentActivator
{
    public WatchedComponentActivator(ComponentModel model, IKernel kernel, ComponentInstanceDelegate onCreation, ComponentInstanceDelegate onDestruction)
        : base(model, kernel, onCreation, onDestruction)
    {
    }

    protected override object CreateInstance(CreationContext context, ConstructorCandidate constructor, object[] arguments)
    {
        object component = base.CreateInstance(context, constructor, arguments);

        if (arguments != null)
        {
            IWatchDogService watchDogService = arguments.FirstOrDefault(arg => arg is IWatchDogService) as IWatchDogService;
            if (watchDogService != null)
            {
                watchDogService.WatchingType = component.GetType();
            }
        }

        return component;
    }
}

class Program
{
    static void Main(string[] args)
    {
        IWindsorContainer container = new WindsorContainer();
        container.AddFacility<WatchDogFacility>();

        container.Register(
            Component.For<IWatchDogService>()
                .ImplementedBy<WatchDogService>()
                .LifestyleTransient(),
            Component.For<WatchedClassViaConstructor>()
        );

        WatchedClassViaConstructor obj = container.Resolve<WatchedClassViaConstructor>();
        obj.Print();
        Console.ReadLine();
    }
}

}

If you're into AOP and like to have your classes remain clutter free, you can use a slightly modified version of the above that lets your watched classes look like this:

public class WatchedClassViaInheritance : WatchedClass
{
    public void Print()
    {
        Console.WriteLine(this.WatchDogService.WatchingType.Name);
    }
}

This uses the same tactics, but uses property injection. I've created a component model construction contributor to enforce castle to require IWatchDogServcie to be injected much like you'd be required to do if it was constructor injection. Here's the code for that:

namespace ComponentCreater2
{
using Castle.Core;
using Castle.MicroKernel;
using Castle.MicroKernel.ComponentActivator;
using Castle.MicroKernel.Context;
using Castle.MicroKernel.Facilities;
using Castle.MicroKernel.ModelBuilder;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public interface IWatchDogService
{
    Type WatchingType { get; set; }
}

public class WatchDogService : IWatchDogService
{
    public Type WatchingType { get; set; }
}

public interface IIsWatched
{
    IWatchDogService WatchDogService { get; set; }
}

public abstract class WatchedClass : IIsWatched
{
    public IWatchDogService WatchDogService { get; set; }
}

public class WatchedClassViaInheritance : WatchedClass
{
    public void Print()
    {
        Console.WriteLine(this.WatchDogService.WatchingType.Name);
    }
}

public class WatchDogFacility : AbstractFacility
{
    protected override void Init()
    {
        this.Kernel.ComponentModelCreated += Kernel_ComponentModelCreated;
        this.Kernel.ComponentModelBuilder.AddContributor(new RequireWatchDogService());
    }

    private void Kernel_ComponentModelCreated(ComponentModel model)
    {
        if (typeof(IIsWatched).IsAssignableFrom(model.Implementation))
        {
            model.CustomComponentActivator = typeof(WatchedComponentActivator);
        }
    }
}

public class WatchedComponentActivator : DefaultComponentActivator
{
    public WatchedComponentActivator(ComponentModel model, IKernel kernel, ComponentInstanceDelegate onCreation, ComponentInstanceDelegate onDestruction)
        : base(model, kernel, onCreation, onDestruction)
    {
    }
    protected override void SetUpProperties(object instance, CreationContext context)
    {
        base.SetUpProperties(instance, context);

        IIsWatched watched = instance as IIsWatched;

        if (watched != null)
        {
            watched.WatchDogService.WatchingType = instance.GetType();
        }
    }
}

public class RequireWatchDogService : IContributeComponentModelConstruction
{
   public void ProcessModel(IKernel kernel, ComponentModel model) 
   { 
       model.Properties.Where(prop => prop.Dependency.TargetType == typeof(IWatchDogService))
           .All(prop => prop.Dependency.IsOptional = false); 
   } 
}


class Program2
{
    static void Main(string[] args)
    {
        IWindsorContainer container = new WindsorContainer();
        container.AddFacility<WatchDogFacility>();

        container.Register(
            Component.For<IWatchDogService>()
                .ImplementedBy<WatchDogService>()
                .LifestyleTransient(),
            Component.For<WatchedClassViaInheritance>()
        );

        WatchedClassViaInheritance obj = container.Resolve<WatchedClassViaInheritance>();
        obj.Print();
        Console.ReadLine();
    }
}

}

3
  • Trying to understand how facilities work... Your WatchDog facility seems to push forward the WatchedComponentActivator regardless of the component type. Would this play nicely with other facilities? What if I registered the TypedFactoryFacility at the same time? Nov 9, 2013 at 10:02
  • I'm not sure if it would work or not. The OP didn't have a common base class or interface to do the appropriate selection, so I couldn't do much about it. With the second example above I took the liberty of having a common interface which allowed my facility to be more selective about what components it provides a custom activator for. Nov 9, 2013 at 15:33
  • 1
    I took the first example and tested creating WatchClassViaConstructor using a typed factory and it worked fine. Nov 9, 2013 at 15:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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