Tag Archives: Design Patterns

A Unit of Work with Repositories Underpinned by DbContext – The DAL

An index of the HomeLibrary application posts can be found here.

I want to have a quick discussion about data access, as I have already re-factored this code in the HomeLibrary application. Originally, I just put in place a couple of simple repositories which looked like this:
Generalised Base Class

public abstract class RepositoryBase<T, TCxt> : IDisposable
	where T : class
	where TCxt : DbContext, new()
{
	public DbContext Context;
	public DbSet<T> Items;

	protected RepositoryBase()
		: this(new TCxt())
	{
		
	}

	protected RepositoryBase(TCxt context)
	{
		Context = context;
		Items = Context.Set<T>();
	}

	public T Create()
	{
		CheckDisposed();
		return Items.Create();
	}

	public void Add(T item)
	{
		CheckDisposed();
		Items.Add(item);
		Context.SaveChanges();
	}

	public T GetById(int id)
	{
		CheckDisposed();
		var set = Items.Find(id);
		return set;
	}

	public void Remove(T item)
	{
		CheckDisposed();
		Items.Remove(item);
		Context.SaveChanges();            
	}

	public void Update(T item)
	{
		CheckDisposed();

		var entry = Context.Entry(item);
		if (entry.State == EntityState.Detached)
		{
			Items.Attach(item);
			entry.State = EntityState.Modified;
		}
		Context.SaveChanges();            
	}
	
	public IList<T> GetAll()
	{
		CheckDisposed();
		return Items.ToList();
	}

	public abstract void CheckDisposed();

	public void Dispose()
	{
		if (!Context.TryDispose()) return;
		Context = null;
		Items = null;
	}
}

Domain-centric Repositories would Inherit from the Base Class

public class BookRepository : RepositoryBase<Book, HomeLibraryContext>, IBookRepository 
{
	public BookRepository()	{ }

	public BookRepository(HomeLibraryContext ctx) 
		: base(ctx)
	{ }

	public override void CheckDisposed()
	{
		if (Context == null)
		{
			throw new ObjectDisposedException("BookRepository");
		}
	}
}

I had a feeling there would be some better stuff out there which facilitated the repository-style access to the data via the DbContext. After a bit of searching, I stumbled upon this answer at stackoverflow. You can go there to read the code if you like (or here for my version), as it is quite large and not practical for me to repeat here.

It uses a unit of work to centralise access through a number of repositories. I liked the idea of this and when I went through the code, I recognised that it was quite sophisticated and written by someone who had really thought it through (and probably incorporated some hard learnt lessons). I made a couple of changes which I preferred, as I don’t just accept someone else’s code without scrutiny. I tagged that revision of the source DataAccessAndDomain_1.1, so it is available to download or read online.

This is definitely overkill for a simple book-lending application. However, I want to endeavour to use enterprise best practices for this sample application.

Twisting the Triad – MVC

I have spent a lot of time researching the difference between the MVC and MVP design patterns, as I could not really articulate those differences in a conversation, even though I have used them both in practice. When asking around, I found that a lot of other developers also did not actually know the difference either. So I was in good company.

When you go down this road, you encounter the phrase “Twisting the Triad”. The MVP pattern was arrived at by “Twisting the Triad” (among other things). But the many people who talk about twisting the triad never actually stop to explain what that means exactly. And when I started asking colleagues what is meant by that phrase, I was not surprised to find that no-one (not 1) person could explain what twisting the triad means. Rotating the nodes in the diagram is not quite good enough as an explanation because it has no context. And how far are they rotated? ** Blank looks all round **. Some guys thought it had something to do with the arrows in the diagram. Whilst the difference in the directed arrows between the MVC and MVP diagrams does encompass a huge part of the distinction between the 2 patterns, it does not, in any way, explain what “Twisting the Triad” means.

After much cogitation on the issue, I believed I worked it out one day during my morning shower. But I wanted back-up before I was sure. This theory gave me fresh keywords for Googling and I finally stumbled upon this post by a very well-respected guy in the ASP.NET MVC community. See the last paragraph under the heading The Difference?.

So, without further ado, let me explain what the phrase “Twisting the Triad” means, when used to explain how the MVC pattern evolved into the MVP patten. It is all about which node of the diagram is the first point of contact for the user gesture (or user request). Let me explain with an interactive diagram. The diagram below shows the MVC pattern with the nodes following this colour legend:

  • Red: Model
  • Green: View
  • Yellow: Controller

The arrow represents the user gesture. As you can see, with MVC, the first point of contact for the user gesture is the Controller, which then orchestrates how the application handles that user input.
Now, click the button with the text Twist the Triad!

User Gesture

When you twist the triad by clicking the button, the View now becomes the first point of contact for the user gesture, which is observed by the Presenter i.e. it raises events to the Presenter which then handles those events.

  • Red: Model
  • Green: View
  • Yellow: Presenter

So to recap, this post was about Twisting the Triad. I realise there are other differences between the two patterns. But I’m hoping this post clearly articulates the meaning of “Twisting the Triad”, which so many great developers cannot seem to explain.