Skip to content

Conditional resolution

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

You have to option to specify what conditions must be met in order for a service to be selected during the resolution.

Parent type filter

class Wulfgar : IBarbarian
{
    public Wulfgar(IWeapon weapon)
    { }
}

container.Register<IWeapon, AegisFang>(context => context.WhenDependantIs<Wulfgar>());

The constraint above indicates that Stashbox must choose the AegisFang implementation of the IWeapon interface when Wulfgar is being resolved.

Attribute filter

If you set an attribute filter for your registration, Stashbox will inject it only, if the dependency is decorated with that attribute:

class NeutralGoodAttribute : Attribute { }
class ChaoticEvilAttribute : Attribute { }

class Drizzt : IDrow
{
    [Dependency, NeutralGood]
    public IPatron Patron { get; set; }
}

class Yvonnel : IDrow
{
    [Dependency, ChaoticEvil]
    public IPatron Patron { get; set; }
}

container.Register<IPatron, Mielikki>(context => context.WhenHas<NeutralGood>());
container.Register<IPatron, Lolth>(context => context.WhenHas<ChaoticEvil>());

Custom user-defined filter

You can specify custom filters with the When(...) configuration expression e.g.:

class Drizzt : IDrow
{
	public IPatron Patron { get; set; }
}

class Yvonnel : IDrow
{
	public IPatron Patron { get; set; }
}

container.Register<IPatron, Mielikki>(context => context.When(t => t.ParentType.Equals(typeof(Drizzt))));
container.Register<IPatron, Lolth>(context => context.When(t => t.ParentType.Equals(typeof(Yvonnel))));