Skip to content

General definition binding

Wojtek edited this page Jun 24, 2013 · 6 revisions

By default, Setter Injection or Constructor Injection methods allows to bind target property/argument to value, object reference or inline object definition using predefined methods like ToValue(), ToInlineDefinition() or ToRegisteredXXX().

Spring.FluentContext is offers also to use more generic (and extendable) method to bind dependencies, which is To() method, accepting parameter of IDefinition<T> type. This method allows to bind target property/argument to any definition that matches to target type.

Currently there are two classes offering IDefinition<T> implementations: IObjectRef<T> and Def class.

The IObjectRef<T> implements now IDefinition<T> itself, so it can be used with To() method to define a reference to other object in context.

The Def class that offers various types of definitions, such as:

  • Reference() to define a reference to other object in context (equivalent of ToRegisteredDefault() and ToRegistered(string objectId)),
  • Value() to define plain value (equivalent of ToValue()),
  • Object() to define unnamed, inline object definition (equivalent to ToInlineDefinition())
  • ObjectProperty() to retrieve property value of other registered object (equivalent of ToObjectProperty() extension method),
  • ToArray() to define array collection, holding definitions of items,
  • ToList() to define list collection, holding definitions of items,
  • ToDictionary() to define dictionary collection, holding definitions of key and value pairs,

The collection definitions are descried in next chapter.

Def.ObjectProperty() method allows to configure object dependencies with property value of other registered object:

ctx.RegisterDefault<Cat>()
	.BindConstructorArg<string>().ToValue("Kitty");

var josephine = ctx.RegisterUniquelyNamed<PersonWithCat>()
	.UseConstructor((string name, Cat cat) => new PersonWithCat(name, cat))
		.BindConstructorArg().ToValue("Josephine")
		.BindConstructorArg().ToRegisteredDefault()
	.GetReference();

ctx.RegisterDefault<PersonWithCat>()
	.UseConstructor((string name, Cat cat) => new PersonWithCat(name, cat))
		.BindConstructorArg().ToValue("Josh")
		.BindConstructorArg().ToObjectProperty(josephine, j => j.Cat) // <-- refers to Josephine's cat
	.GetReference();

Continue reading: 16. Collection injection

Clone this wiki locally