Skip to content

Conditional resolution

Peter Csajtai edited this page Jul 11, 2019 · 19 revisions

You have the option to specify what conditions must be met 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 AegisFang when Wulfgar is being resolved.

Attribute filter

If you set an attribute filter for your registration, Stashbox will use it only, when a dependency is decorated with the given 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>())
         .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))));