Skip to content

Resolution by attributes

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

You have the option to use some pre-defined attributes to get more control over the dependency resolution.

Constructor injection

If you have multiple registrations for a service type, you can specify which one should be chosen by the container with the Dependency attribute.

class Drizzt : IDrow
{
    public Drizzt([Dependency("Twinkle")]IWeapon leftHand, [Dependency("Icingdeath")]IWeapon rightHand)
    {
        //...
    }
}

container.Register<IWeapon, Twinkle>("Twinkle")
         .Register<IWeapon, Icingdeath>("Icingdeath");

Member injection

The Dependency attribute also can be used for property and field injection.

class Drizzt : IDrow
{
    [Dependency("Icingdeath")]
    public IWeapon RightHand { get; set; }
	
    [Dependency("Twinkle")]
    private IWeapon leftHand;
}

container.Register<IWeapon, Twinkle>("Twinkle")
         .Register<IWeapon, Icingdeath>("Icingdeath");

Injection method

The InjectionMethod attribute can be used to specify which methods you want to get called when the container resolves the service.

class Drizzt : IDrow
{
    [InjectionMethod]
    public void CallGuenhwyvar([Dependency("orcs")]IEnumerable<ICreature> targets)
    {
        //...
    }
}