65.9K
CodeProject is changing. Read more.
Home

Integrating Spring.NET with ASP.NET Web Site

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.86/5 (48 votes)

Jan 26, 2008

CPOL

5 min read

viewsIcon

156854

downloadIcon

2169

This article describes how to integrate Spring.NET enterprise Framework with ASP.NET

Introduction

Developing software applications is hard enough even with good tools and technologies. It is said by Spring.NET developers that Spring provides a lightweight solution for building enterprise-ready applications. Spring provides a consistent and transparent means to configure your application and integrate Aspect-Oriented Programming (AOP) into your software. Highlights of Spring's functionality are providing declarative transaction management for your middle tier as well as a full-featured ASP.NET Framework.

According to them, Spring.NET is an application Framework that provides comprehensive infrastructural support for developing enterprise .NET applications. It allows you to remove incidental complexity when using the base class libraries which makes best practices, such as test driven development, easy practices. Spring.NET is created, supported and sustained by SpringSource.

Environment Setup

First download Spring.NET from Sourceforge Spring.NET download page. While writing this article, the latest version was 1.1. Install it at default location.

The ASP.NET Web Site

To start with Spring.NET, let us create a new Web site. We have a Default.aspx page. Now we need to create sections in Web.Config files.

<configuration><configSections><!-- Spring --><sectionGroupname="spring"><sectionname="context"type="Spring.Context.Support.WebContextHandler, Spring.Web"/><sectionname="objects"type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/><sectionname="parsers"type="Spring.Context.Support.NamespaceParsersSectionHandler, Spring.Core"/></sectionGroup></configSections><!-- Spring --><spring><parsers></parsers><context><resourceuri="config://spring/objects"/></context><objectsxmlns="http://www.springframework.net"xmlns:db="http://www.springframework.net/database"><!-- Pages --><objecttype="Default.aspx"></object></objects></spring><sysyem.web><httpHandlers><!-- Spring Handler --><addverb="*"path="*.aspx"type="Spring.Web.Support.PageHandlerFactory, Spring.Web"/></httpHandlers><httpModules><addname="SpringModule"type="Spring.Context.Support.WebSupportModule, Spring.Web"/></httpModules></sysyem.web></configuration>

We have now added a new HTTP handler for *.aspx pages that is a Spring.NET provided handler. Now Spring.NET manages all our ASP.NET pages. We'll be able to use Spring.NET features for the ASP.NET pages after this configuration.

Now we have to add a reference to the site. We need a reference to Spring.Core and Spring.Web assembly located in the Spring.NET installation folder. We can now run the application to see our page. We'll go to the next step if everything is OK.

Dependency Injection

DI is a very interesting thing. You can make your design totally decoupled with concrete implementations. To see this in effect, let us create a new string type property in our page's code named Message with a private variable message. And in the Page_Load method, add the following line:

Response.Write(message);

Here we do not set the value of the message variable. We'll set it through the Web.Config file. We now change the object definition for Default.aspx:

<objecttype="Default.aspx"><propertyname="Message"value="Hello from Web.Config"/></object>

Now we have supplied a value outside of the page using the configuration file. We have set a string type value here. We can also set an object type value. To do that, let us define a class Math with one method:

publicclass Math { publicint add(int x, int y) { return x+y; } }

Now let us add a new property Math in the Default.aspx code file like we did for message. In the Page_Load method, we add code:

Response.Write(math.add(30, 50));

In Web.Config we now add new object definition just above object for Default.aspx. So our spring section becomes:

<spring><parsers></parsers><context><resourceuri="config://spring/objects"/></context><objectsxmlns=http://www.springframework.netxmlns:db="http://www.springframework.net/database"><objectname="MyMathObj"type="Math, App_code"/><!-- Pages --><objecttype="Default.aspx"><propertyname="Message"value="Hello from Web.Config"/><propertyname="Math"ref="MyMathObj"/></object></objects></spring>

Working with Data

Now we want to deal with data. To deal with data, Spring.NET natively provides NHibernate and ADO.NET support. Here we use NHibernate - as it handles all dirty things about database and lets us work in the object world only. In the Spring.NET installation folder in /bin and in /lib directory, we have the required NHibernate binaries. Here I use NHibernate 1.2 assemblies. For hibernate we define a table in the database named person, create a new class named Person and a NHibernate mapping file (Person.hbm.xml):

The Person Table

ColumnTypeModifiers
IdNumbernot null, primary key
VersionNumberNumber-
Namenvarchar(16)not null

The Person Class

publicclass Person { privatelong id; privatestring name; privateint versionNumber; //These methods should be virtual for NHibernate Mappingpublicvirtuallong Id { get { return id; } set { id = value; } } publicvirtualint VersionNumber { get { return versionNumber; } set { versionNumber = value; } } publicvirtualstring Name { get { return name; } set { name = value; } } }

The NHibernate Mapping File

<?xmlversion="1.0"encoding="utf-8"?><hibernate-mappingxmlns="urn:nhibernate-mapping-2.2"namespace="CodeProject.DAO"assembly=""CodeProject.DAO"><classname="Person"table="Person"><idname="Id"><columnname="Id"not-null="true"/><generatorclass="increment"/></id><versioncolumn="VersionNumber"name="VersionNumber"/><propertyname="Name"><columnname="Name"length="16"not-null="true"/></property></class></hibernate-mapping>

Please note that the mapping file should have the extension .hbm.xml and should be set to Embedded Resource for Build Action property of the file.

The BaseDAO Class

We want a base class that implements basic functionality of database like LoadALL, SaveOrUpdate etc. We define an Interface and implement that for our use:

publicinterface IBaseDAO<EntityT, idT> { IList LoadAll(); EntityT LoadByID(idT id); IList Load(string hsqlQuery, object[] values); void Save(EntityT fine); void SaveOrUpdate(EntityT fine); NHibernate.ISessionFactory SessionFactory { set; } } publicabstractclass BaseDAO<EntityT, idT>: IBaseDAO<EntityT, idT> { protected HibernateTemplate hibernateTemplate; public ISessionFactory SessionFactory { set { hibernateTemplate = new HibernateTemplate(value); hibernateTemplate.TemplateFlushMode = TemplateFlushMode.Auto; } } public BaseDAO() { } publicvirtual EntityT LoadByID(idT id) { EntityT entity = (EntityT)hibernateTemplate.Load(typeof(EntityT), id); return entity; } publicvirtual IList LoadAll() { return hibernateTemplate.LoadAll(typeof(EntityT)); } publicvirtual IList Load(string hsqlQuery, object[] values) { return hibernateTemplate.Find(hsqlQuery, values); } publicvirtualvoid Save(EntityT fine) { hibernateTemplate.Save(fine); } publicvirtualvoid SaveOrUpdate(EntityT fine) { hibernateTemplate.SaveOrUpdate(fine); } }

The PersonDAO Class

This class is inherited from BaseDAO that is responsible for the Person class's load/save operation:

publicinterface IPersonDAO : IBaseDAO<Person, long> { } publicclass PersonDAO : BaseDAO<Person, long>, IPersonDAO { }

Please note that this time we define the class with Person type for Object type and use long for Id type.

Using the PersonDAO Object

Now we add a new property to Default.aspx code file named personDAO. Please note here that you must use the interface of DAO class here.

IPersonDAO personDAO; public IPersonDAO PersonDAO { get{return personDAO;} set{personDAO=value;} }

And add the following line in the Page_Load method:

Person p = new Person(); p.Name = "Maruf"; personDAO.Save(p); Person p1 = personDAO.LoadByID(1); 

You may do whatever you want with the Person object you get.

Configuration for NHibernate

Now we need some configuration work in Web.Config file.

<?xmlversion="1.0"?><configuration><configSections><!-- Spring --><sectionGroupname="spring"><sectionname="context"type="Spring.Context.Support.WebContextHandler, Spring.Web"/><sectionname="objects"type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/><sectionname="parsers"type="Spring.Context.Support.NamespaceParsersSectionHandler, Spring.Core"/></sectionGroup></configSections><!-- Spring --><spring><parsers><parsertype="Spring.Data.Config.DatabaseNamespaceParser, Spring.Data"/></parsers><context><resourceuri="config://spring/objects"/></context><objectsxmlns=http://www.springframework.netxmlns:db="http://www.springframework.net/database"><db:providerid="DbProviderMySQL"provider="MySql"connectionString="Server=localhost;....;"/><objecttype="Spring.Objects.Factory.Config.PropertyPlaceholderConfigurer, Spring.Core"><propertyname="ConfigSections"value="databaseSettings"/></object><objectid="SessionFactory"type="Spring.Data.NHibernate.LocalSessionFactoryObject, Spring.Data.NHibernate12"><propertyname="DbProvider"ref="DbProviderMySQL"/><propertyname="MappingAssemblies"><list><value>CodeProject.DAO</value></list></property><propertyname="HibernateProperties"><dictionary><entrykey="hibernate.connection.provider"value="NHibernate.Connection.DriverConnectionProvider"/><entrykey="hibernate.dialect"value="NHibernate.Dialect.MySQLDialect"/><entrykey="hibernate.connection.driver_class"value="NHibernate.Driver.MySqlDataDriver"/></dictionary></property></object><objectname="MyMathObj"type="Math, App_code"/><objectid="PersonDAO"type="CodeProject.DAO.PersonDAO, CodeProject.DAO"><propertyname="SessionFactory"ref="SessionFactory"/></object><!-- Pages --><objecttype="Default.aspx"><propertyname="Message"value="Hello from Web.Config"/><propertyname="Math"ref="MyMathObj"/><propertyname="PersonDAO"ref="PersonDAO"/></object></objects></spring><appSettings/><connectionStrings/><system.web><compilationdebug="true"/><authenticationmode="Windows"/><httpHandlers><!-- Spring Handler --><addverb="*"path="*.aspx"type="Spring.Web.Support.PageHandlerFactory, Spring.Web"/></httpHandlers><httpModules><addname="SpringModule"type="Spring.Context.Support.WebSupportModule, Spring.Web"/><!-- Required for managing NHibernate session between http requests--><addname="OpenSessionInView"type="Spring.Data.NHibernate.Support.OpenSessionInViewModule, Spring.Data.NHibernate12"/></httpModules></system.web></configuration>

Declarative Transaction Management

It keeps transaction management out of business logic, and is not difficult to configure in Spring. We want our certain operation be under transaction. We do not need to manage that in code. We simply configure that from Web.Config file. Let us assume we want Save, SaveOrUpdate, Delete, Query etc. method in PersonDAO to be in atomic database operation and rollback entire operation on any exception. We create PersonDAOTx object in our config file and set it to the Deafult.aspx pages' PersonDAO property.

<!-- TxManager --><objectid="HibernateTransactionManager"type="Spring.Data.NHibernate.HibernateTransactionManager, Spring.Data.NHibernate12"><propertyname="DbProvider"ref="DbProviderMySQL"/><propertyname="SessionFactory"ref="SessionFactory"/></object><objectid="PersonDAOTx"type="Spring.Transaction.Interceptor.TransactionProxyFactoryObject, Spring.Data"><propertyname="PlatformTransactionManager"ref="HibernateTransactionManager"/><propertyname="Target"ref="PersonDAO"/><propertyname="TransactionAttributes"><name-values><addkey="Save*"value="PROPAGATION_REQUIRES_NEW"/><addkey="SaveO*"value="PROPAGATION_REQUIRES_NEW"/><addkey="Delete*"value="PROPAGATION_REQUIRED"/><addkey="Update*"value="PROPAGATION_REQUIRED"/><addkey="Query*"value="PROPAGATION_REQUIRED"/></name-values></property></object><!-- Pages --><objecttype="Default.aspx"><propertyname="Message"value="Hello from Web.Config"/><propertyname="Math"ref="MyMathObj"/><propertyname="PersonDAO"ref="PersonDAOTx"/></object>

Please note that we can use a new transaction or an inherited transaction from the caller. While using inherited transaction, a new transaction is automatically created if none exists from the caller.

Web Service

Spring introduces very flexible Web service support. It can export any class that implements a public interface. WebService attribute is not required at all. Let us define a plain interface and implement it in a plain class:

publicinterface IFirstService { string GetMessage(); } publicclass FirstService : IFirstService { privatestring message; publicstring Message { get { return message; } set { message = value; } } publicstring GetMessage() { return message; } } 

That's it. We can now export this class by just adding a few lines in the Web.Config file. We can also inject its dependency (the Message property) from web.config. Please note the new httpHandlers entry to handle.asmx page.

<objectid="FirstServiceImpl"type="CodeProject.DAO.FirstService, CodeProject.DAO"><propertyname="Message"value="Test Message"/></object><!--Web Services--><objectid="FirstService"type="Spring.Web.Services.WebServiceExporter, Spring.Web"><propertyname="TargetName"value="FirstServiceImpl"/><propertyname="Namespace"value="http://myCompany/services"/><propertyname="Description"value="My First web service"/></object><system.web><httpHandlers><!-- Spring --><addverb="*"path="*.aspx"type="Spring.Web.Support.PageHandlerFactory, Spring.Web"/><addverb="*"path="*.asmx"type="Spring.Web.Services.WebServiceHandlerFactory, Spring.Web"/></httpHandlers></system.web>

That's it. We can access the service at /FirstService.asmx path.

By now we can create ASPX pages, Web services without [WebService] attribute from virtually any class, inject dependency from configuration file - making the application highly configurable, work with database and totally separate the transaction management from business logic. I expect it will help to quickstart using Spring.NET and develop a scalable application. For beginners, when you use Spring.NET for the first time you'll be surprised how much it helps by reducing most of the redundant work. Please excuse for language - my first language is Bangla. I'll be happy to hear from you.

close