Skip to content
Suremaker edited this page Dec 11, 2012 · 4 revisions

For many cases object dependency configuration is very straightforward. There is usually per one object of given type in context and it is being injected to all objects which needs it.

It is possible to simplify such configurations to objects registration and allowing Spring to resolve all obvious dependencies automagically (see notes at the end of section).

The following code presents the same configuration written without and with autowiring:

// Configuration without autowiring
ctx.RegisterDefault<Endpoint>();

ctx.RegisterDefault<Consumer>()
	.UseConstructor((IEndpoint endpoint) => new Consumer(endpoint))
		.BindConstructorArg().ToRegisteredDefault();

ctx.RegisterDefault<Sender>()
	.UseConstructor((IEndpoint endpoint) => new Sender(endpoint))
		.BindConstructorArg().ToRegisteredDefault();

// Configuration with autowiring
ctx.RegisterDefault<Endpoint>();

ctx.RegisterDefault<Sender>()
	.Autowire();

ctx.RegisterDefault<Consumer>()
	.Autowire();

The above example shows how configuration could be simplified with using Autowire() method. If it is used, Spring tries to resolve all object dependencies. There is an overloaded version of Autowire() method, accepting Spring.Objects.Factory.Config.AutoWiringMode enum and allows to set one of following modes (please see Table 5.3. Autowiring modes for details):

  • No - autowiring is disabled,
  • ByName - autowires by name, ie. injects object which id is the same as target property name,
  • ByType - autowires by type, ie. injects object which type is matching to type of property,
  • Constructor - autowires by constructor parameters, ie. tries to match objects to constructor parameters using type comparison,
  • Autodetect - autowires using Constructor or ByType if default constructor is found.

The parameterless version of Autowire() uses Autodetect mode.

It is worth to say that if object is configured with autowiring and some explicit injections, explicit DI would be used for those dependencies which have it.

Please note that by default autowiring is OFF

Please also note that Lookup Method Injection has to always be used explicitly.

It has been written that with autowiring, all dependencies are resolved automagically. The reason why this name was used is because with autowiring, dependency resolving is done behind the scene, so object dependencies are no longer as easy to track and understand. It is also more difficult to determine if all needed objects are registered or if all of them are still being used. Generally it is not recommended to use this behavior for large configuration.

*Please also read [12. Dependency checking](Dependency checking) section which describes how to ensure that object have all dependencies resolved.

For more details, please see 5.3.6. Autowiring collaborators

Continue reading: 11. Initialization and finalization

Clone this wiki locally