Skip to main content

Spring.net and asp.mvc, Getting started with dependency injection

This small tutorial gives you the quickest route (that i know) to getting microsofts mvc working with spring.net for simple DI (Dependency injection) or IOC (Inversion of control) to aid in testing and maintanance. Yes i know spring.net can do much more but this is just a very basic how to.

Download Prerequesits
First get asp.mvc, download and install from here (im assuming you have vs2008 or like wise for this tutorial)
http://www.asp.net/mvc/download/
At the time of writing im using vs2008, xp and mvc 1
downloaded here
http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=53289097-73ce-43bf-b6a6-35e00103cb4b
but im sure mvc 2.0 would be much the same to set up DI

right click on your existing solution (or alternativly create a new one)
then add, new project, web, pick 'asp.net mvc web appication' from the list of templates contained
this will make a brand new mvc web app, all configured and ready to go, build and run it you should see the default mvc site out of the box.
now to get spring running and injecting goodness into it.

first download spring.net
http://www.springframework.net/download.html
im going for the latest production release 1.3.0

then download MVCContrib from
http://mvccontrib.codeplex.com/
im using the latest stable release for mvc 1.0 here
http://mvccontrib.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=33401
get both the main download and the extras package (the spring IOC assembalies are contained in the extras package)

reference the following assemblies from the solution: spring.core, mvcContrib and MCVContrib.spring

Substitute the default controller factory for the spring factory provided by mvcContrib
Add the following to the head of global.ascx
using Spring.Context.Support;
using MvcContrib.Spring;

add IOC to your global.ascx so that application_start creates a spring context

protected void Application_Start()
{
ConfigureIoC();
RegisterRoutes(RouteTable.Routes);
}

private static void ConfigureIoC()
{
ContextRegistry.RegisterContext(new XmlApplicationContext(false, "assembly://MvcApplication1/MvcApplication1/objects.xml"));

var ctx = ContextRegistry.GetContext();
SpringControllerFactory.Configure(ctx);

ControllerBuilder.Current.SetControllerFactory(typeof(SpringControllerFactory));
}

add an objects.xml file that will hold all the spring configuration

<?xml version="1.0" encoding="utf-8"?>
<objects xmlns="http://www.springframework.net"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.net
http://www.springframework.net/xsd/spring-objects.xsd">
</objects>

This objects.xml must be an embedded resource into the assembly, right click the file, properties, and change it to an embedded resource. If you miss this step you will get an error stating 'Could not load file or assembly Spring.Core.....' basically stating that the assembly didn't contain the objects.xml, which is the dependency spring is looking for.

at this point if you ran the code you would get the error
No object named 'HomeController' is defined : Cannot find definition for object [HomeController]
This is good, it means that spring is looking for a definition of your home controller but cant find one.
so letes tell it about it

add this to your objects xml
<object id="HomeController" type="MvcApplication1.Controllers.HomeController, MvcApplication1">
</object>


now when you run the app you should get the same boring default mvc home page again, brilliant, looks like its working, now to test the dependency injection, this is what we have been waiting for.

Inject a custom object into the homeController
So the easiest way to demo this is to echo some text out onto the screen that comes from a dummy data
add 2 objects to the model folder

using System;
namespace MvcApplication1.Models
{
public interface IHelloDAO
{
String Hi();
}
}

namespace MvcApplication1.Models
{
public class HelloDAO : IHelloDAO
{
public string Hi()
{
return "This is data straight from HelloDAO";
}
}
}



now we are going to use this DAO (Data Access Object) in the controller to get some data from the model by using the Hi method on the IHello interface.
the class should now look like this
public class HomeController : Controller
{
public IHelloDAO HelloDAO { get; private set; }

public HomeController(IHelloDAO helloDAO)
{
HelloDAO = helloDAO;
}

public ActionResult Index()
{
//ViewData["Message"] = "Welcome to ASP.NET MVC!";
ViewData["Message"] = HelloDAO.Hi();

return View();
}

public ActionResult About()
{
return View();
}
}


We added a new constructor which takes an instance of IHelllo (this is the think that is being injected in), and we have used the instance to get the message by using HelloDAO.Hi()
finally import the relevent model namespace at the top of the file.

again if you were to run the app at this point you would get the following error:
Cannot instantiate a class that does not have a no-argument constructor [MvcApplication1.Controllers.HomeController].
which indicates quite clearly that the controller is not configured correctly. Basically spring is expecting a no argument constructor, but the real class dosent have one.

Configure Spring
Now all that remains is to wire the dependencies in the objects.xml which should now look like this

<?xml version="1.0" encoding="utf-8"?>
<objects xmlns="http://www.springframework.net"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.net
http://www.springframework.net/xsd/spring-objects.xsd">

<object id="HomeController" type="MvcApplication1.Controllers.HomeController, MvcApplication1">
<constructor-arg ref="HelloDAO" />
</object>

<object id="HelloDAO" type="MvcApplication1.Models.HelloDAO, MvcApplication1">
</object>
</objects>

you can see we have added a parameterised constructor to the controller through wich we are injecting in an implementation of the HelloDAO interface.
The index remains the same as it was out of the box and should display our message instead of the default 'Welcome to ASP.NET MVC!'

lets run it.
magic, you have configured your first and hopefully not last controller through spring.net and asp.mvc

now your ready for part 2 (Spring.net and asp.mvc, even more dependency injection)

Facebook

Facebook Recommendations

Followers


Web Designing In Karachi



Haroof.com


Politics blogs

My Zimbio

Email Subscribe

Enter your email address:

Watch online Live TV

Popular posts from this blog

BRITISH FIRM TO INTRODUCE DISSOLVABLE POLYTHENE BAGS IN KARACHI.

CNews Karachi. July 05: A Pakistani Scientist in Britain has invented a new chemical for processing plastic (polythene) bags which has the quality of dissolution after its use in 105 days.A manufacturing unit for these plastic bags was being set up in Turkey while interest has been shown in the setting up of a big unit and manufacturing firm’s head quarter in Karachi which will be used to supply such dissolvable polythene bags to Asian countries. The Director of UK based firm Bio Plast Biodegradable Plastics GL Punn while leading a 15 member delegation called on EDO Municipal Services City Government Masood Alam. The Executive Director of Bio Plast Pakistan Muhammad Hanif Awan and M. Sultan Mehmood Awan was also present on this occasion. The Director of Bio Plast informed the EDO Municipal Services about the characteristics of new chemical. He said that the firm was going to set up its first plant in Turkey which will be operative in next two months. The delegation also praised the vi

Admission Open in Class XI in Pre-Engineering, Pre-Medical, and Commerce Groups at BODMAS MODEL COLLEGE, North Nazimabad, Karachi

  Admission Open in Class XI in Pre-Engineering, Pre-Medical, and Commerce Groups at BODMAS MODEL COLLEGE, North Nazimabad, Karachi.

Matric General Group Result SECONDARY SCHOOL CERTIFICATE (S. S. C.) PART - II CLASS - X - 2010 (www.apnieyesp.com )

PASSED THE SECONDARY SCHOOL CERTIFICATE (S. S. C.) PART - II CLASS - X) ANNUAL EXAMINATION, 2010. ERRORS AND OMISSIONS EXCEPTED, CANDIDATES BEARING THE FOLLOWING ROLL NUMBERS ARE DECLARED TO HAVE PASSED THE SECONDARY SCHOOL CERTIFICATE (S. S. C.) PART - II CLASS - X) ANNUAL EXAMINATION, 2010. ------------------------------------------------- GENERAL GROUP (REG&PVT) --- GRADE..'A-ONE' ---- ----------------------- ( CANDIDATES SECURING TOTAL MARKS 680 AND ABOVE) MARKS SECURED BY THE CANDIDATES OUT OF TOTAL MARKS OF 850 ARE MENTIONED AGAINST EACH ROLL NUMBER IN BRACKET --------------------------------------------------- 601086 (689) XXX (XXX) XXX (XXX) XXX (XXX) XXX (XXX) XXX (XXX) 601327 (681) 363 (684) 364 (719) 407 (685) 664 (682) 788 (687) 601836 (692) 882 (683) XXX (XXX) XXX (XXX) XXX (XXX) XXX (XXX) 602315 (723) 316 (715) 320 (712) 321 (739) 325 (686) 326 (702) 602327 (683) 329 (70

Labels

Show more