Clean, Better, and Sexier Generic Repository Implementation for Entity Framework

With the new release of the GenericRepository.EntityFramework package, we now have clean, better and sexier generic repository implementation for Entity Framework. Enjoy!
2013-01-10 13:00
Tugberk Ugurlu

I have written a few blog posts about my experience on applying the Generic Repository pattern to Entity Framework and I even made a NuGet package for my naïve implementation. Even if that looked OK at the time for me, I had troubles about my implementation for couple of reasons:

  • The implementations inside the NuGet package didn’t allow the developer to share the DbContext instance between repositories (per-request for example).
  • When the generic repository methods weren’t enough, I was creating new repository interfaces and classes based on the generic ones. This was the biggest failure for me and didn’t scale very well as you can imagine.
  • There were no pagination support.
  • As each repository take a direct dependency on DbContext and it is impossible to entirely fake the DbContext, generic repositories needed to be mocked so that we could test with them. However, it would be just very useful to pass a fake DbContext instance into the repository implementation itself and use it as fake.

With the new release of the GenericRepository.EntityFramework package, the all of the above problems have their solutions. The source code for this release is available under the master branch of the repository and you can also see the ongoing work for the final release under the v0.3.0 branch. The NuGet package is available as pre-release for now. So, you need to use the –pre switch to install it.

PM> Install-Package GenericRepository.EntityFramework -Pre

The old GenericRepository.EF package is still around and I will update it, too but it’s now unlisted and only thing it does is to install the GenericRepository.EntityFramework package.

I also included a sample application which shows the usage briefly. I will complete the sample and extend it further for a better view. Definitely check this out!

Let’s dive right in and see what is new and cool.

IEntity and IEntity<TId> Interfaces

I introduced two new interfaces: IEntity and IEntity<TId> and each of your entity classes needs to implement one of these. As you can see from the implementation, IEntity just implements the IEntity<int> and you can use IEntity if you are using integer based Ids. The reason why I added these is make the GetSingle method work.

Use EntitiesContext Instead of DbContext

Instead of deriving your context class from DbContext, you now need to take the EntitiesContext as the base class for your context. If you have an existing context class based on DbContext, changing it to use EntitiesContext should not break it. The EntitiesContext class has all the same constructors as DbContext. So, you can also use those. Here is the sample:

public class AccommodationEntities : EntitiesContext {

    // NOTE: You have the same constructors as the DbContext here. E.g:
    // public AccommodationEntities() : base("nameOrConnectionString") { }

    public IDbSet<Country> Countries { get; set; }
    public IDbSet<Resort> Resorts { get; set; }
    public IDbSet<Hotel> Hotels { get; set; }

Then, through your IoC container, you can register your context as a new instance for IEntitiesContext per a particular scope. The below example uses Autofac to do that for an ASP.NET Web API application:

private static void RegisterDependencies(HttpConfiguration config) {

    var builder = new ContainerBuilder();

    // Register IEntitiesContext
    builder.Register(_ => new AccommodationEntities())

    // TODO: Register repositories here

    config.DependencyResolver = 
        new AutofacWebApiDependencyResolver(builder.Build());

IEntityRepository<TEntity> and EntityRepository<TEntity>

Here is the real meat of the package: IEntityRepository and EntityRepository. Same as the IEntity and IEntity<TId>, we have two different IEntityRepository generic interfaces: IEntityRepository<TEntity> and IEntityRepository<TEntity, TId>. They have their implementations under the same generic signature: EntityRepository<TEntity> and EntityRepository<TEntity, TId>. The big improvement now is that EntityRepository generic repository implementation accepts an IEntitiesContext implementation through its constructor. This, for example, enables you to use the same DbContext (IEntitiesContext implementation in our case, which is EntitiesContext by default) instance per-request for your ASP.NET MVC, ASP.NET Web API application and share that across your repositories. Note: don’t ever use singleton DbContext instance throughout your AppDomain. DbContext is not thread safe.

As we have registered our EntitiesContext instance per request above, we can now register the repositories as well. As our repositories accepts an IEntitiesContext implementation through their constructor, our IoC container will use our previous registration for that automatically. Autofac has this ability as nearly all IoC containers do.

private static void RegisterDependencies(HttpConfiguration config) {

    var builder = new ContainerBuilder();

    // Register IEntitiesContext
    builder.Register(_ => new AccommodationEntities())

    // TODO: Register repositories here

    config.DependencyResolver = 
        new AutofacWebApiDependencyResolver(builder.Build());

Out of the Box Pagination Support

Best feature with this release is out of the box pagination support with generic repository instances. It doesn’t perform the pagination in-memory; it queries the database accordingly and gets only the parts which are needed which is the whole point Smile Here is an ASP.NET Web API controller which uses the pagination support comes with the EntityRepository:

public class CountriesController : ApiController {

    private readonly IEntityRepository<Country> _countryRepository;
    private readonly IMappingEngine _mapper;
    public CountriesController(
        IEntityRepository<Country> countryRepository, 
        IMappingEngine mapper) {

        _countryRepository = countryRepository;
        _mapper = mapper;

    // GET api/countries?pageindex=1&pagesize=5
    public PaginatedDto<CountryDto> GetCountries(int pageIndex, int pageSize) {

        PaginatedList<Country> countries = 
             _countryRepository.Paginate(pageIndex, pageSize);

        PaginatedDto<CountryDto> countryPaginatedDto = 
           _mapper.Map<PaginatedList<Country>, PaginatedDto<CountryDto>>(countries);

        return countryPaginatedDto;

public interface IPaginatedDto<out TDto> where TDto : IDto {

    int PageIndex { get; set; }
    int PageSize { get; set; }
    int TotalCount { get; set; }
    int TotalPageCount { get; set; }

    bool HasNextPage { get; set; }
    bool HasPreviousPage { get; set; }

    IEnumerable<TDto> Items { get; }

public class PaginatedDto<TDto> : IPaginatedDto<TDto> where TDto : IDto {

    public int PageIndex { get; set; }
    public int PageSize { get; set; }
    public int TotalCount { get; set; }
    public int TotalPageCount { get; set; }

    public bool HasNextPage { get; set; }
    public bool HasPreviousPage { get; set; }

    public IEnumerable<TDto> Items { get; set; }

Paginate method will return us the PaginatedList<TEntity> object back and we can project that into our own Dto object as you can see above. I used AutoMapper for that. If I send a request to this API endpoint and ask for response in JSON format, I get back the below result:

        "Name":"United Kingdom",

Isn’t this perfect Smile There are other pagination method inside the EntityRepository implementation which supports including child or parent entities and sorting. You also have the ToPaginatedList extension method and you can build your query and call ToPaginatedList on that query to get PaginatedList<TEntity> object back.

Extending the IEntityRepository<TEntity>

In my previous blog posts, I kind of sucked at extending the generic repository. So, I wanted to show here the better approach that I have been taking for a while now. This is not a feature of my generic repository, this is the feature of .NET itself: extension methods! If you need extra methods for your specific repository, you can always extend the IEntityRepository<TEntity, TId> which gives you a better way to extend your repositories. Here is an example:

public static class HotelRepositoryExtensions {

    public static IQueryable<Hotel> GetAllByResortId(
        this IEntityRepository<Hotel, int> hotelRepository, int resortId) {

        return hotelRepository.FindBy(x => x.ResortId == resortId);

What is Next?

My first intention is finish writing all the tests for the whole project, fix bugs and inconsistencies for the v0.3.0 release. After that release, I will work on EF6 version for my generic repository implementation which will have sweet asynchronous support. I also plan to release a generic repository implementation for MongoDB.

Stay tuned, install the package, play with it and give feedback Winking smile

Sides and Source Code for DEU Bilgisayar Topluluğu Izmir 2. Teknoloji Zirvesi

This weekend, I participated in an event as a speaker in Izmir, DEU Bilgisayar Topluluğu Izmir 2. Teknoloji Zirvesi. Sides and Source Code for my sessions are available.
2013-01-08 04:34
Tugberk Ugurlu

This weekend, I participated in an event as a speaker in Izmir. I also had the chance to meet Fatih Boy, İkay İlknur, Umut Erkal and Oğuzhan Yılmaz at the event. There were great sessions throughout the first and second day.



I gave two talks during the event and one of them was on Git and GitHub. You can see the slides for that session below:

At the second day, I talked about asynchronous programming for .NET server applications. Slides for that session is also available on my SpeakerDeck page. You can also get the source code for the demos:

JavaScript-Heavy, Maintainable Web Applications by a n00b: 101 - Leveraging Existing Libraries

I decided to dedicate this part of my life to JavaScript for a while and I will write my experience on JavaScript-heavy, maintainable web Applications as a n00b.
2013-01-08 00:07
Tugberk Ugurlu

Nearly every software developer dedicates a part of its time to improve him/herself on a particular area of expertise. Well, I dedicate this part of my life to JavaScript for a while. I have been writing JavaScript for approx. 3 years now but if anybody asks me if I know JavaScript, I tell them that I know JavaScript and I *don’t* know JavaScript at the same time. It’s probably because of the fact that I don’t get to work with it that much. One of the places I struggle most is the idea of maintaining big-ass JavaScript heavy web applications. That idea has been causing me to carry a psychic weight but now, at this very moment, I am committed to throw it away like a piece of garbage! And yes, it starts with a blog post Smile

A few months ago I talked to a brilliant developer about node.js, the platform built on Chrome's JavaScript runtime (V8) for easily building fast, scalable network applications, and asked his opinion about it. He was uncertain at the time but apparently he had more information about node.js than me. So, I expressed that I didn’t understand the need of JavaScript at the server side because it’s hard to maintain such a huge JS codebase. Then, he slapped me in the face with a follow-up sentence: "Well, the node community thinks that a big application codebase needs to be separated into small modules, components to be more maintainable". That was the nudge I needed to believe that the JavaScript codebase can be maintained.

Not long time later from that moment, I then started watching John Papa’s Single Page Apps with HTML5, Web API, Knockout and jQuery and I learnt lots of mind blowing stuff about JavaScript: new (at least new to me) libraries, well-known JavaScript patterns, which I had been aware of but didn’t know how to apply them most of the time, and many more. This was the start of my commitment to learn JavaScript (I mean really learning, going beyond the for loops and if statements) and I pulled out my JavaScript: The Good Parts book which I have bought in last June, but I thought that the best way to learn this stuff is to blog about it. So, here I am Winking smile In this post I am listing a few JavaScript libraries which make a lot of sense to be used in nearly every web applications. I have been working with some of this libraries for a while now and I am going to be working with some of those.

JQuery: The JavaScript framework we all know and fell in love at the time that we have noticed it. JQuery is especially helpful for DOM manipulation and Ajax interactions. If you don’t want to install JQuery, don’t worry; you eventually will have to because I am sure that at least of the libraries you are going to use will have a dependency on it.

KnockoutJS: KnockoutJS is one of the best things that can happen to a web developer. Starting to learn KnockoutJS gives you the equivalent feeling which you would feel at the very moment when you find a cup of hot chocolate in a freezing cold day. It enables your to have two way data-binding between your DOM elements and your view model which means when your data model's state changes, your UI updates automatically and vice versa. Check out its well-arranged documents and live tutorials.

Underscore.js: Underscore.js provides a utility suite which covers lots of useful functions. From the its official page: "Underscore provides 80-odd functions that support both the usual functional suspects:map, select, invoke — as well as more specialized helpers: function binding, javascript templating, deep equality testing, and so on. It delegates to built-in functions, if present, so modern browsers will use the native implementations of forEach, map,reduce, filter, every, some and indexOf". Don’t forget to watch this awesome presentation from Elijah Manor on Underscore.js.

RequireJS: I think RequireJS is the essential piece of library which makes it possible to have maintainable, well-designed JavaScript codebase. It’s a modular script loader which enables you to write small pieces of code in separate files and handle their dependencies and load order correctly. RequireJS also has a very nice documentation in its web site; definitely check that out.

Sammy.js: Last library I am considering for my every web application is Sammy.js. It gives us a nice way to handle page navigations without refreshing the page at all by providing a nice routing mechanism. Especially, if you are writing a Single Page Applications (SPA), this is the library that you want inside your suite. Don’t skip to check out its intro sample.

There are for sure other great libraries out there (e.g. Moment.js, AmplifyJS, JQuery UI, Breeze) but these are the ones I am in love at the moment. Go check them out and start exploring Winking smile

List of Resources on Asynchronous Programming for .NET Server Applications with C#

I listed some resources on asynchronous programming for .NET server applications with C# which consist of blog posts, presentations and podcasts.
2013-01-05 22:01
Tugberk Ugurlu

I will be participating on an event today in Izmir talking about asynchrony for .NET server applications (mostly ASP.NET) and I thought it would be great to list some reference blog posts, presentations and podcasts on this topic as there are a few distinct resources regarding asynchrony as I listed below.

In my talk, I plan to mix some stuff from previous @StevenSanderson, @DamianEdwards, @LeviBroderick, @bradwilson presentations and blog posts. I have also bunch of demos which I will be sharing online in my GitHub repository. So, enjoy the resources for now Winking smile

Resources for Asynchrony in General

Resources for Asynchrony for Server Applications

DEU Bilgisayar Topluluğu Izmir 2. Teknoloji Zirvesi

DEU Bilgisayar Topluluğu Izmir 2. Teknoloji Zirvesi: if you are in Izmir this weekend (5 – 6 January, 2013), don’t miss this event.
2013-01-03 10:43
Tugberk Ugurlu

If you are in Izmir this weekend (5 – 6 January, 2013), don’t miss this event. Me, Fatih Boy, İlkay İlknur and Umut Erkal will be giving talks on several interesting topics.

Facebook event page: