Skip to content

Generic wrappers

Peter Csajtai edited this page Jan 3, 2020 · 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")
         .Register<ICreature, Drow>("Drizzt")
         .Register<ICreature, Human>("Catti-brie")
         .Register<ICreature, Barbarian>("Wulfgar")
         .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<>

container.Register<IWeapon, Twinkle>();

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