Archive for the 'MonoRail' Category

Using the Repository Pattern with ActiveRecord from Castle

I first learned about ActiveRecord (AR) when I was introduced to the MonoRail framework made by Castle. Then a few years later I started to learn about Domain-Driven Design (DDD) and found that is was an interesting way to design software. Just like so many other software design techniques, DDD also uses design patterns and one of them is the Repository Pattern.

Repository - A mechanism for encapsulating storage, retrieval, and search behaviour which emulates a collection of objects.
Eric Evans, Domain-driven design

Usually when you use ActiveRecord from Castle, then your entities would have to inherit from a base class like ActiveRecordBase, but in this example we don’t need to do that anymore.

You need to have some basic understanding of ActiveRecords, NHibernate and the Repository Pattern to implement the example.

1
2
3
4
5
6
7
public interface IRepository<T>
{
	T FindBy(Guid id);
	IList<T> FindAll();
	void Save(T item);
	void Delete(T item);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class RepositoryBase<T> : IRepository<T> where T : IAggregateRoot
{
 
	public T FindBy(Guid id)
	{
		return (T)ActiveRecordMediator.FindByPrimaryKey(typeof(T), id);
	}
 
	public IList<T> FindAll()
	{
		return (IList<T>)ActiveRecordMediator.FindAll(typeof(T));
	}
 
	public virtual void Save(T item)
	{
		ActiveRecordMediator.Save(item);
	}
 
	public virtual void Delete(T item)
	{
		ActiveRecordMediator.Delete(item);
	}
}

The IAggregateRoot is just a marker interface, meaning that it doesn’t specify any functionality. I know that this might look like “code smell” to some, but it really depends on what you are trying to achieve.

Custom attributes are preferred when you can defer checking for the attribute until the code is executing. If your scenario requires compile-time checking, you cannot comply with this guideline.
- MSDN, Guidelines for developing Class libraries.

The problem with using AR with DDD

Well, PI means clean, ordinary classes where you focus on the business problem at hand without adding stuff for infrastructure-related reasons.
Applying DDD and Patterns, Jimmy Nilsson

Using AR will you get up and running pretty fast, but you might want to remove the AR parts later on and then re-implement your repository to only use NHibernate. The reason for this is that entities shouldn’t know about how they are persisted (i.e. Persistence Ignorance) and when you apply them with AR attributes they do.

If you want to achieve a higher Persistence Ignorance, then you could try out Ayende’s Rhino-Tools (also know as rhino-commons). There you can find a better implementation of the Repository Pattern, which also uses NHibernate. Another solution would of course be to create one your self.

Further reading

Domain-Driven Design: Tackling Complexity in the Heart of Software

Applying Domain-Driven Design and Patterns: With Examples in C# and .NET

How to setup Dependency Injection with Microsoft Unity in Asp.net Mvc

Dependency Injection (DI) is a pretty great technique that will help you decouple a service from a client. The way it works, is that when a client is created a service will be applied in the instantiation of the client, so that it holds a reference to the service. You can of course inject multiple services, if you want to.

The description of DI might be a bit vague, because the term service seems to be used for anything these days. I hope the examples will shed some light on it.

Let’s see how things will look like without DI - This can of course be done a bit differently, but for the sake of the example we will just keep it like this.

1
2
3
4
5
6
7
8
9
public class HomeController : Controller
{
	public void Index()
	{
		ISomeRepository repo = new SomeRepository();
		ViewData["content"] = repo.FindContent();
		return View();
	}
}

Let’s move on to an example where DI comes into play.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class HomeController : Controller
{
	private ISomeRepository repo;
 
	public HomeController(ISomeRepository someRepository)
	{
		repo = someRepository;
	}
 
	public void Index()
	{
		ViewData["content"] = repo.FindContent();
		return View();
	}
}

We need to do a little bit more than this. So let’s download Unity from Microsoft and include it in our project. Then we can create a new ControllerFactory.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class UnityControllerFactory : DefaultControllerFactory
{
	private readonly IUnityContainer _container;
 
	public UnityControllerFactory(IUnityContainer container)
	{
		_container = container;
	}
 
	protected override IController GetControllerInstance(Type controllerType)
	{
		if (controllerType == null)
		{
			throw new HttpException(0x194, "No Controller Found");
		}
 
		if (!typeof(IController).IsAssignableFrom(controllerType))
		{
			throw new ArgumentException("TypeDoesNotSubclassControllerBase", 
				"controllerType");
		}
 
		return _container.Resolve(controllerType) as IController;
	}
}

So far, so good. We will now set it up in the Global.asax file. Of course, you will need to create some sort of service, if you want to test this. In my example I assume that I have a service called SomeRepository available to me, which implements the interface ISomeRepository.

1
2
3
4
5
6
7
8
protected void Application_Start()
{
	IUnityContainer container = new UnityContainer();
	container.RegisterType<ISomeRepository, SomeRepository>();
 
	UnityControllerFactory factory = new UnityControllerFactory(container);
	ControllerBuilder.Current.SetControllerFactory(factory);
}

That’s it! You have now injected your first service into a Controller.

The great thing about this is that you can now unit test your controllers with a mock implementation of a service, as long as it implements the interface.

If you have been using MonoRail, then you probably know about Windsor, so if you don’t like to use Unity, you can easily switch Unity out.

Ps. Using DI can be a good thing, but using it extensively can make things too complex, which is a bad thing.

Using Json with the SmartDispatcherController in MonoRail

In a previous article I gave an example of how powerfull the SmartDispatcherController can be, but you can do a lot more with it. You can actually map your Json objects to your objects in the C# code, when you parse it to one of your actions.

1
2
3
4
5
6
public struct JSONObject
{
	public string Var1;
	public string Var2;
	public int[] Var3;
}

There is nothing new here, so moving on.

1
2
3
4
5
6
7
8
9
new Ajax.Request("/base/testJSON.rails", { 
   method: 'post',
   parameters: { JSONObject: Object.toJSON( {Var1: 'Hello World', 
                                            Var2: 'Something else', 
                                            Var3: [1,2,4]} ) },
   onSuccess: function(transport) { 
      alert(transport.responseText);
   }
});

If you are new to Prototype, this might look a bit strange, but what it basically does is that it makes an ajax request and parse a Json object as the parameter.

1
2
3
4
public void testJSON([JSONBinder("JSONObject")] JSONObject myJsonObject)
{
	// Do something
}

The biggest change here, from my previous example, is that instead of using the DataBind attribute, we apply the JSONBinder attribute.

If you want to try this out, then you should reference the Castle.MonoRail.JSONSupport.dll and the Newtonsoft.Json.dll. The last one can be found in the external-dependencies.zip file.

Next Page »