Skip to content

Service registration

Peter Csajtai edited this page May 14, 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:

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

If there are multiple services mapped to an interface, ReMap will replace all of them with the given one, 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 type of registration will tell the container, that it should execute further operations (member injection, container extensions, etc.) on the registered instance.

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

Injection parameters

If you have some special parameters in your services constructor which you'd like to set manually (primitive types for example, or some pre-evaluated values) you can use injection parameters.

class Drizzt : IDrow
{
    public Drizzt(IWeapon leftHand, IWeapon rightHand)
    {
        //...
    }
}
container.Register<IWeapon, Twinkle>();
container.Register<IDrow, Drizzt>(context => context.WithInjectionParameters(new InjectionParameter { Value = new Icingdeath(), Name = "rightHand" });

The configuration above indicates that Stashbox will inject the pre-evaluated Icingdeath object as Drizzts right-hand weapon and the other one will be resolved through the standard registration.