Skip to content

Generic wrappers

Peter Csajtai edited this page Nov 6, 2018 · 8 revisions

Lazy<>

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

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 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();

Tuple<>

var tuple = container.Resolve<Tuple<IDrow, IWeapon>>();
var drizzt = tuple.Item1;
var twinkle = tuple.Item2;