Skip to content

Service registration

Peter Csajtai edited this page Jul 9, 2019 · 16 revisions

Standard

The following example shows how you can bind your service to an interface or abstract base class.

container.Register<ICreature, Elf>();
//or without generic parameters
container.Register(typeof(ICreature), typeof(Elf));

The container will resolve the Elf type as an ICreature.

You can also register a service to itself, without specifying a base.

container.Register<Elf>();
//or without generic parameters
container.Register(typeof(Elf));

Named

If you want to bind more implementations to a service type you have the option to differentiate them by names:

container.Register<ICreature, Dwarf>("Bruenor");
container.Register<ICreature, Drow>("Drizzt");

The name parameter is an object so it can be anything else, not just string.

Instance

In some cases, you may want to use already instantiated services as dependencies:

var elf = new Elf();
container.RegisterInstanceAs<ICreature>(elf);

The container will always return with the prepared instance when an ICreature is requested.

ReMap

Stashbox supports the remapping of already registered services.

Important: If there are multiple services mapped to an interface, ReMap() will replace all of them with the current one.

container.Register<IDwarf, Bruenor>();
container.ReMap<IDwarf, Pwent>();

If you want to replace only one specified service, use the ReplaceExisting() configuration e.g. container.Register<IDwarf, Bruenor>(context => context.ReplaceExisting());

WireUp

Similar to the Instance registration except that this will tell the container, that it should execute further operations (member injection, container extensions, etc.) on the registered instance during resolution.

var elf = new Elf();
container.WireUp<ICreature>(elf);

Injection parameters

If you already have some pre-evaluated dependencies which you'd like to use at resolution time, then you can set them as injection parameters for your service.

class Drizzt : IDrow
{
    public Drizzt(IWeapon leftHand, IWeapon rightHand)
    {
        //...
    }
}

container.Register<IDrow, Drizzt>(context => context
    .WithInjectionParameter("rightHand", new Icingdeath()
    .WithInjectionParameter("leftHand", new Twinkle());