Avoid cryptic errors with Setter injection and Spring.Net

Today I found out about a really neat feature in the Spring.Net framework that can help enormously with debugging Spring.Net configuration problems.

If you are using setter injection and have properties that need to be set (why aren’t you using constructor injection?) then you should decorate those properties with the [Required] attribute. You then need to add a built in post processor to your application configuration like so:
<object type=”Spring.Objects.Factory.Attributes.RequiredAttributeObjectPostProcessor, Spring.Core”><object/>

Now if you forget to configure one of your required properties instead of getting a cryptic dependancy error like this:

Spring.Objects.Factory.ObjectCreationException: Error thrown by a dependency of object ‘myWidget’ defined in ‘assembly [Widgets, Version=, Culture=neutral, PublicKeyToken=null], resource [Widgets.application-config.xml]’ : Initialization of object failed : Object reference not set to an instance of an object.
while resolving ‘constructor argument’ to ‘otherWidget’ defined in ‘assembly [Widgets, Version=, Culture=neutral, PublicKeyToken=null], resource [Widgets.application-config.xml]

You get a nice helpful error like this:

Spring.Objects.Factory.ObjectInitializationException: Property ‘OtherWidget’ required for object ‘myWidget’

Much more helpful!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s