Skip to content

Conditional resolution

Peter Csajtai edited this page Mar 14, 2017 · 19 revisions

If you want to specify in which cases you want to inject some special dependencies, you can use the conditional resolution feature of Stashbox.

Parent type filter

class Wulfgar : IBarbarian
{
	[Dependency]
	public IWeapon Weapon { get; set; }
}

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

The constraint above indicates that Stashbox will 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.PrepareType<IPatron, Mielikki>().WhenHas<NeutralGood>().Register();
container.PrepareType<IPatron, Lolth>().WhenHas<ChaoticEvil>().Register();

Custom user-defined filter

You can specify custom filters yourself if you decorate your registration with When(...) calls e.g.:

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

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

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

Clone this wiki locally