Sehab
Sehab

Reputation: 259

Castle Windsor Multiple Implementation For Same Inteface in MVC

If I have multiple implementations of the same interface eg: IRule, how would I be able to resolve it in my controller?

private readonly IRule[] _rules;

public HomeController(IRule[] rules)
{
    _rules = rules;
}

public RunRules() 
{
    foreach (IRule rule in rules)
        rule.RunRule();
}

Upvotes: 2

Views: 1582

Answers (1)

Sehab
Sehab

Reputation: 259

I ran into an issue where I wanted to set up my controller to pull in a collection of rules, but didn't want to list each rule by itself so I had an array of IRule[] that I set up.

Controller:

private readonly IRule[] _rules;

public HomeController(IRule[] rules)
{            
     _rules = rules;
}

Installer:

Set up castle windsor installer.

public void Install(IWindsorContainer container, IConfigurationStore store)
{
    container.Register(Component.For<IRule>().ImplementedBy<ValidateNPIRule>());
    container.Register(Component.For<IRule>().ImplementedBy<ValidateZipRule>());
}

The important part was the line to .AddSubResolver Adding in the CollectionResolver was what I needed for the installer to resolve all of my rules at once and I could pull them in an array.

Global.asax:

protected void Application_Start()
{
    WindsorContainer container = new WindsorContainer();

    container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel, true));
    container.Install(FromAssembly.This());
}

Upvotes: 4

Related Questions