-
Notifications
You must be signed in to change notification settings - Fork 2
Object definition registration
It is possible to register object definition in four different ways.
var ctx = new FluentApplicationContext();
ctx.RegisterDefault<Cat>();
var cat = ctx.GetObject<Cat>();
The example above shows registration of object definitions using RegisterDefault() method. It registers object with default ID and it is very useful if context will contain only one definition for given class or if this definition would be mostly used in application or injections.
It is also possible to register object definitions with specified id. This method is useful if context would contain more than one definition for given class, or if this identifier is used later in code or child context.
The example below shows usage of RegisterNamed() method and extension method allowing to get specific object:
var ctx = new FluentApplicationContext();
ctx.RegisterNamed<Cat>("Kitty");
ctx.RegisterNamed<Cat>("Misty");
var kitty = ctx.GetObject<Cat>("Kitty");
var misty = ctx.GetObject<Cat>("Misty");
The RegisterUniquelyNamed() method allows to register definition with generated unique name. It is useful if context would contain more definitions for same class, however their ids are not used directly as literals in code or child contexts. The generated id can be accessed by calling GetReference() method. Those definitions can be also used in autowiring (described later). There is also an extension method that allows to retrieve object by its reference.
var ctx = new FluentApplicationContext();
var cat1Ref = ctx.RegisterUniquelyNamed<Cat>().GetReference();
var cat2Ref = ctx.RegisterUniquelyNamed<Cat>().GetReference();
var cat1 = ctx.GetObject(cat1Ref);
var cat2 = ctx.GetObject(cat2Ref);
Last type of object registration methods is dedicated for already instantiated objects. Because such objects are already created and configured, it is only possible to register them as singletons and optionally retrieve their ids. Similarly to other registration methods, this one is also present in three variations: RegisterDefaultSingleton(), RegisterNamedSingleton() and RegisterUniquelyNamedSingleton().
var ctx = new FluentApplicationContext();
ctx.RegisterDefaultSingleton(new Cat("Kitty"));
ctx.RegisterDefault<PersonWithCat>()
.BindProperty(p => p.Cat).ToRegisteredDefault();
return ctx;
Objects registered with those methods are used to resolve dependencies of other objects in exactly same way as ones registered in different way.
Continue reading: 4. Object scope