Skip to content

Multi resolution

Peter Csajtai edited this page Nov 6, 2018 · 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.Register<ICreature, Dwarf>("Bruenor");
container.Register<ICreature, Drow>("Drizzt");
container.Register<ICreature, Human>("Catti-brie");
container.Register<ICreature, Barbarian>("Wulfgar");
container.Register<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 injected into constructor/member/method:

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 in which form you want to get the requested collection:

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

//etc...