Skip to content

Generic wrappers

Peter Csajtai edited this page Feb 16, 2017 · 8 revisions

##Lazy<> If you need something lazy loaded, just ask Stashbox and it'll wrap your service into a Lazy<> type.

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 your service lazy loaded in the following way:

var lazyMemberOfTheCompanionsOfTheHall = container.Resolve<Lazy<ICreature>>("Regis");

This works for every other injection type as well.

class CompanionsOfTheHall
{
	[Dependency("Regis")]
	public Lazy<ICreature> Regis { get; set; }

	public CompanionsOfTheHall([Dependency("Bruenor")]ICreature bruenor, [Dependency("Drizzt")]ICreature drizzt, [Dependency("Catti-brie")]ICreature cattibrie, [Dependency("Wulfgar")]ICreature wulfgar)
	{
		//...
	}
}

##Func<> You can also use the Func<> resolution feature of the container, which allows factory delegate resolution with parameter injection override.

var lazyMemberOfTheCompanionsOfTheHallFactory = container.Resolve<Func<ICreature>>("Regis");
var regis = lazyMemberOfTheCompanionsOfTheHallFactory();