Search code examples
c#reflectioncastle-windsor

Passing requesting class type to a requested class constructor


Let's say I have a following class:

public class Handler
{
    public Type RequesterType { get; }

    public Handler(Type requesterType)
    {
        RequesterType = requesterType;
    }
}

which is itself a dependency of another class:

public class Controller
{
    public Handler Handler { get; }

    public Controller(Handler handler)
    {
        Handler = handler;
    }
}

Is it possible to register Handler in such a way that when Controller is being resolved, the dependent Handler's constructor argument requesterType is being assigned with Controller type?

Here's an example of what I want to achieve:

class Program
{
    static void Main(string[] args)
    {
        var container = new WindsorContainer();
        container.Register(
            Component.For<Controller>()
            //Component.For<Handler>(), <- this is the essense of my question
        );

        var controller = container.Resolve<Controller>();
        Console.WriteLine(controller.Handler.RequesterType); //Should output Program.Controller
        Console.ReadKey();
    }
}

Solution

  • A common way to handle this would be to make Handler generic:

    public class Handler<T>
    {
        public Type RequesterType { get { return typeof(T) ; }
    }
    

    Then instead of passing the type in the constructor, you'd pass it as a generic type parameter:

    public class Controller
    {
        public Handler<Controller> Handler { get; }
    
        public Controller(Handler<Controller> handler)
        {
            Handler = handler;
        }
    }
    

    Now you can register your handlers per controller in the usual way, and they will resolve for the right type.

    You may want to embellish this a bit with interfaces or covariance, but that is the general idea.