Skip to content

Multi resolution

Peter Csajtai edited this page May 10, 2017 · 13 revisions

Mapping to the same type

When you want to register multiple implementations of a service, you can differentiate them with a given name:

container.RegisterType<ICreature, Dwarf>("Bruenor");
container.RegisterType<ICreature, Drow>("Drizzt");
container.RegisterType<ICreature, Human>("Catti-brie");
container.RegisterType<ICreature, Barbarian>("Wulfgar");
container.RegisterType<ICreature, Halfling>("Regis");

Then you can get all of your services by calling the ResolveAll() method:

var companionsOfTheHall = container.ResolveAll<ICreature>();

Injecting multiple services

You can also get all implementations of a service as constructor/member/method injected:

class CompanionsOfTheHall
{
    [Dependency]
    public IReadOnlyCollection<ICreature> Members { get; set; }

    public CompanionsOfTheHall(IEnumerable<ICreature> members)
    { }
	
    //or
	
    public CompanionsOfTheHall(ICreature[] members)
    { }

    //or
	
    public CompanionsOfTheHall(ICollection<ICreature> members)
    { }

    //etc...
}

Result type

You can also specify the result type when you requesting from the container directly:

var companions = container.Resolve<IEnumerable<ICreature>>();
//or
var companions = container.Resolve<ICreature[]>();
//or
var companions = container.Resolve<IReadOnlyCollection<ICreature>>();

//etc...