Tuesday, January 6, 2009

QuickStart: Spring.NET Dependency Injection With ASP.NET

Spring.NET is a .NET port of the popular Spring framework for Java, and is most commonly used for implementing dependency injection in applications. In today's example, I'll demonstrate the usage of Spring.NET for defining a validator onto an ASP.NET page.

Let's start off by creating an ASP.NET Web Application Project. (Click the images to enlarge them and view the code snippets)

Step 1: Add References to Spring.Core and Spring.Web
Add Spring.Core and Spring.Web Reference

You can download the binaries for Spring.NET 1.2.0 here and add references to Spring.Core and Spring.Web

Step 2: Declare the spring sectionGroup in the configSections of the web.config file

Spring.NET sectionGroup in the ASP.NET web.config

Declare the context and objects sections within the spring sectionGroup in the web.config file. The context section is used to define the configuration for the Spring IoC container and the objects section is used to define objects.

Step 3: Add the spring configuration to the web.config file

IoC container declaration in web.config

In the context section, refer to the objects resource within the spring section of the ASP.NET Web.config file. Within objects, define the validation group NameValidation containing a required validator. Inject an instance of NameValidation to the NameValidator property of the Default.aspx page.

Step 4: Declare the PageHandlerFactory HTTP handler and the WebSupportModule HTTP module in the web.config

PageHandlerFactory HTTP handler

WebSupportModule HTTP module
Assuming you are working with a pre-IIS 7 web application server, you can declare the PageHandlerFactory HTTP handler and the WebSupportModule HTTP module as indicated above.

Step 5: Add a textbox and button to your page

Test user interface for Spring.NET validation
Create the user interface to enter a name on the page.

Step 6: Add the necessary 'plumbing'

Adding the code-behind
Create a Name property wrapper for the textbox created in Step 5. Add the NameValidator property. Define the button event handler to validate the data in the textbox and display the validation status.

Run the application! When the user leaves the textbox blank, the validation returns false; else it returns true.

1 comment:

Bruno said...

Nice article, simple and very understandable.