Windsor Container Factory Facility

This is a real cool facility that I just used in my Hybrid CMS. There is a full in depth walkthrough on BitterCoder’s Blog here but I will describe how I used it in this blog post.

I needed to be able to have the kernel instantiate a specific implementation of IAuthService. This Interface has a couple of method definitions, but most important it had the Authenticate() method. The idea behind this is that I can swap out IAuthService and change the way a user is authenticated. At the moment Active Directory and Database is supported.

So in the whole architecture I have the following classes/interfaces

  • IAuthService
  • DbAuthService : IAuthService (component id: db.authService)
  • AdAuthService : IAuthService (component id: ad.authService)

In the Castle config section for Windsor, they have the following component Id’s listed above. Both of these component declarations have factory=authServiceFactory which activation of the components are deferred to at runtime.

In the AppSettings section I have an Application Setting called authStore=db.authService, which just has whichever component will be used for authentication.

Here is the code for AuthServiceFactory to give you an idea how the AuthService’s are returned from the kernel:


public class AuthServiceFactory : IAuthServiceFactory 


private IKernel _kernel;public AuthServiceFactory(IKernel kernel) { 

_kernel = kernel; 


protected string AuthStoreType 

{ get { return ConfigurationManager.AppSettings["authStoreType"]; } 


public IAuthService Create() 


return (IAuthService)_kernel.Resolve(AuthStoreType, typeof(IAuthService)); 



Pretty cool huh? Now if I want to introduce a new method of Authentication I only need to add the component to the config file, make an implementation and select it in the AppSetting. Very flexible! =)


Ajax and MonoRail

This is a repost of an example I created for using.castleproject.orgI just used some Ajax functionality on another project and I figured I would post some code of what I found out after struggling with a couple of pieces for awhile.MonoRail utilizes the Prototype Javascript Framework to perform Ajax calls, so worst case scenario, you can write javascript code directly against the prototype library. All you need to do on your MonoRail view is include the javascript declaration by placing the following at the top of your view:


First, You’ll need to look at the Castle Project AjaxHelper documentation. You don’t need to memorize the whole thing, but pay close attention to LinkToRemote and ButtonToRemote. There is ALOT of stuff in there, so try not to feel overwhelmed. I know I did at first =)For my project, I had to input some price information, add the price to a collection on the controller, and then display it on the view before continuing. The easiest way to do this is to serialize the form and pass it when performing the Ajax call, Ajax then invokes an Action on your controller, and you respond by either rendering some text, or rendering another view into the “update” div. Here is my code for my ButtonToRemote: 

$AjaxHelper.ButtonToRemote("Add Price", "addprice.rails", $DictHelper.CreateDict("update=prices","with=Form.serialize($('itemform'))"))

 Let’s step through the parameters one by one.

  • “Add Price”
    • This is the text that will be shown on the button. pretty basic
  • “addprice.rails”
    • This is the action to call on the controller
  • $DictHelper.CreateDict(“update=prices”,“with=Form.serialize($(‘itemform’))”))
    • The dictionary values to pass is where it is a little tricky. “update=prices” is the id of the div that Ajax will update upon sending a response. So if you render text, or another view it will appear within this div id. The second dictionary parameter is for values that you want to pass to your action, hence the with= parameter. You can pass the entire form as I have, or single values such as an id

Note, that I am using $(‘itemform’) instead of ‘this’ when telling the AjaxHelper to serialize the form. This refers to the id value of the form tag. I tried it both ways and it didn’t seem to want to work the other way. Perhaps someone else has a different experience with this. Next, setup your action to do whatever processing you need and then Render a view like so:

public void AddPrice([DataBind("price")] Price price)
// Do some work with price object

The RenderView call will render the view called priceList.vm that is located in the same directory as the Controllers view. Then you have to call CancelLayout to cancel the layout processing which occurs last, otherwise the layout will also be rendered within the div. If you call RenderText it will simply output that text into the div.The reason I am rendering a view into the div is because it is displaying a collection of prices along with edit/delete links for each. In its basic form, the functionality here is the same as an Ajax DataGrid/GridView if we were in the WebForms world, except without the burden of Page lifecycle.On a project I was working on at my workplace, I needed to expand/collapse divs and upon expanding I make an Ajax call to the database to grab the detail view of the expanded div. When I created that, I found it was easier to create a custom javascript function in which I made a call via the prototype library using an Ajax.Request. There are many things you can leverage with using the Prototype framework through MonoRail and the sky is the limit. Check the Castle Project Forum for helpful information, or you can search through the Castle Project Users Newsgroup.Another good place to start is to read the PrototypeJS documentation. This is recommended because all MonoRail is doing is just wrapping the calls to ProtoType. Hopefully in the near future we might see a more rich ajax framework arise from MonoRail, but at the moment I think there is alot more areas that can be focused on within Castle rather than dump time into a custom built Ajax Framework. As they say, If it ain’t broken, then don’t fix it! Not at least until there is a large enough following.

Testing MonoRail Controllers from Castle’s Trunk

Note: This post was on my old blog, but it is linked to and I wanted to move it to my new blog for future reference.Originally, Hammett placed a AbstractMRTestCase in the same namespace to facilitate testing of controllers. This class simulated a browser by supplying the user with access to session, request, response etc… This class didn’t work too well and was clunky to use. The guys at Eleutian came up with their own solution awhile ago that you can read here. This worked by mocking out everything that the Controller class needed using Rhino Mocks. This worked much better, although it was a little tricky to pull down and use yourself.
Enter BaseControllerTest! This works off of Eleutian’s example and makes the whole deal much easier. Here is an example of how you would go about using it.
First, Your Test Fixture must derive from BaseControllerTest. In this example I am testing a SearchController I made for CMS software:

public class SearchControllerTestCases : BaseControllerTest{}

Next, You must instantiate your Controller class. I do this in the SetUp method, as I am using the Controller in more than one test and I don’t want to violate the DRY principle:

public void SetUp()

_mocks = new MockRepository();

_searchService = _mocks.CreateMock();

_searchController = new SearchController(_searchService);

As you can see I am also passing in a mock of a Serivce that is provided by Windsor at runtime. Now we have created our controller and set everything up. Now we are ready to perform our first test. The following test Searches for a Teacher by their username. Note in the test that I make a call to PrepareController. This sets up the controller with the specified area, controller and action. Take a gander at the code for BaseControllerTest class here and it will give you a much better idea of what PrepareController is doing. All it does is setup the IRailsEngineContext by creating instances of mock classes that will respond to your test. Here is the code in my test to perform SearchForTeacher():

[Test]public void CanSearchForTeacher(){IList teachers = new List();PrepareController(_searchController, "", "Search", "FindTeacher");string teacherName = "username";using (_mocks.Unordered()){Expect.Call(_searchService.FindTeacher(teacherName)).Return(teachers);}_mocks.ReplayAll();_searchController.FindTeacher(teacherName);_mocks.VerifyAll();}

So the only mock expectation I need to setup here is for SearchService.FindTeacher that is called when FindTeacher() is called on the controller. If I had values that needed to be set such as PropertyBag values, or CurrentUser. All you need to do is just set them by using the Context variable available through BaseController test like so:

[SetUp]public void SetUp(){MockRepository _mocks = new MockRepository();_webSiteManageController = new WebSiteManageController();_user = _mocks.CreateMock();PrepareController(_webSiteManageController, "manage", "WebSite", "List");Context.CurrentUser = _user;}

Note where I am setting Context.CurrentUser as it is accessed through this Controller on the AuthorizationFilter I have setup on the WebSiteManageController class. This way, everytime the AuthroizationFilter is run, it will return true to allow access to the underlying controller.Hopefully that gives you a jump start on using Castle’s new Controller Test support! Have fun!