Search code examples
c#dependency-injectioncastle-windsor

How to inject proper dependency based on constructor parameter name


I have this interface that is being used by a handful of concrete types, such as EmailFormatter, TextMessageFormatter etc.

public interface IFormatter<T>
{
    T Format(CompletedItem completedItem);
}

The issue I'm having is that with my EmailNotificationService is that I want to inject EmailFormatter. The constructor signature for this service is public EmailNotificationService(IFormatter<string> emailFormatter).

I'm pretty sure I've seen this done before but how do I register this with Windsor so that it injects EmailFormatter if the constructor parameter name is emailFormatter?

Here is my Windsor registration code.

container.Register(Component.For<IFormatter<string>>().ImplementedBy<EmailFormatter>());

Solution

  • Service code:

    public EmailNotificationService(IFormatter<string> emailFormatter){...}
    

    Dependency registration code:

    container.Register(
        Component.For<IFormatter<string>().ImplementedBy<TextMessageFormatter>().Named("TextMessageFormatter"),
        Component.For<IFormatter<string>().ImplementedBy<EmailFormatter>().Named("EmailFormatter"),
        Component.For<INotificationService>().ImplementedBy<EmailNotificationService>().ServiceOverrrides(
            ServiceOverride.ForKey("emailFormatter").Eq("EmailFormatter"))
    );