MonoRail - ASP.NET Model-View-Controller and Windsor Dependency-Injection Integration

MonoRail - ASP.NET Model-View-Controller and Windsor Dependency-Injection Integration

by David Hayden ( Microsoft MVP ), Filed: Castle Project

 

The Castle Team really needs to show off the Windsor Integration in their MonoRail Getting Started Sample Download because I think it is a really sweet feature. It is in the documentation, but a far more beautiful thing to see in action :)

The fact that MonoRail will automatically inject a service in my controller when I simply add the service as a parameter to the constructor and register the service in my configuration file is a huge deal!

 

public class HomeController : SmartDispatcherController
{
    private IMyService _myService;
    public HomeController(IMyService myService)
    {
        _myService = myService;
    }
}

 

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <components>
        <component
            id="MyService"
            service="HelloWorld.Model.IMyService, HelloWorld"
            type="HelloWorld.Model.MyService, HelloWorld" />
    </components>
</configuration>

 

The Web Client Software Factory offers dependency injection, too, but you have to add the service programmatically in the business module or foundation module initializer class:

 

moduleServices.AddNew<MyService,IMyService>();

 

I actually wrote a tutorial on adding services and dependency injection in WCSF:

Registering and Using Business Module Services in the Web Client Software Factory

 

I personally like the configuration file route in MonoRail and hope WCSF has this option in the future, but that is just my preference. Of course, you can add components to Windsor programatically as well.

 

My jaw hit the floor when I realized that the Windsor Integration in MonoRail did setter injection. I tend to prefer constructor injection and perhaps didn't realize Windsor would also check properties. Anyway, MonoRail can automatically inject the service via the property setter as well:

 

public class HomeController : SmartDispatcherController
{
    private IMyService _myService;
    public IMyService MyService
    {
        set { _myService = value; }
    }
}

 

You gotta love that Windsor Integration!

Source: David Hayden ( Microsoft MVP )

Filed: Castle Project

posted on Friday, March 16, 2007 1:59 PM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices