Entity Framework DbContext with Unity IoC

In the past, I have attempted a Unit of Work + Repository architecture. There are arguments that this is duplicate work since DbContext is a UnitOfWork and Repository. I have also found I needed to import the EntityFramework references into my application layer projects (which defeated some of my motivation for abstracting the DbContext).

In my most recent projects I have given up on forcing DbContext into my own Unit of Work and Repository. Now, I extract an IDbContext interface so I can test against mocks more easily.

Package and Framework versions in this article

  1. MVC5
  2. WebApi 2
  3. Entity Framework 6
  4. Unity 4
  5. Unity.Mvc
  6. Unity.AspNet.WebApi
  7. Moq 4


I abstract my own interface so I can mock and test without an actual database.

public class MovieDbContext : DbContext, IMovieDbContext
    public MovieDbContext(string connectionString)
        : base(connectionString)
        // configuration settings

    public virtual IDbSet<Movie> Movies { get; set; }
    public virtual IDbSet<Genre> Genres { get; set; }

    public override void OnModelCreating(DbModelBuilder modelBuilder) { ... }
public interface IMovieDbContext : IDisposable
    IDbSet<Movie> Movies { get; set; }
    IDbSet<Genre> Genres { get; set; }

    int SaveChanges();

Since I’m extending DbContext, IDisposable and SaveChanges() is implemented for me. I add to the interface if my application requires more of the DbContext’s methods.

I Moq this up on my test class

    protected virtual IMovieDbContext GetMockContext(IList<Movie> movies, IList<Genre> genres)
        var dbSetMovies = GetMockDbSet<Movie>(movies);
        var dbSetGenres = GetMockDbSet<Genre>(genres);

        var mockContext = new Mock<IMovieDbContext>();
        mockContext.Setup(m => m.Movies).Returns(dbSetMovies);
        mockContext.Setup(m => m.Genres).Returns(dbSetGenres);

        return mockContext.Object;

    protected virtual IDbSet<T> GetMockDbSet<T>(IList<T> data) where T : class
        var queryable = data.AsQueryable();
        var mockSet = new Mock<IDbSet<T>>();
        mockSet.As<IQueryable<T>>().Setup(m => m.Provider).Returns(queryable.Provider);
        mockSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(queryable.Expression);
        mockSet.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(queryable.ElementType);
        mockSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(queryable.GetEnumerator());
        mockSet.Setup(d => d.Add(It.IsAny<T>())).Callback<T>((s) => data.Add(s));

        return mockSet.Object;

Service Layer

I now can segregate the query code into a service layer. I usually use AutoMapper, but for this example have manual projections.

public class MovieService : IMovieService
    private IMovieDbContext db;

    public MovieService(IMovieDbContext db)
        this.db = db;

    public MovieDto GetMovie(string title)
        var query = db.Movies.Where(m => m.Title == title)
                             .Select(m => new MovieDto { Id = m.Id, Title = m.Title, Year = m.Year });

        var movie = query.FirstOrDefault();

        return movie;

The service easily takes a DbContext mock to test the query logic without connecting to a database.


The controller doesn’t care about the DbContext nor its query logic. The service is injected with the IoC container (Unity).

public class MovieController : Controller
    private IMovieService service;

    public MovieController(IMovieService service)
        this.service = service;

    public ActionResult GetMovie(string title)
        var movie = this.service.GetMovie(title);
        return View("MovieDetail", movie);

Unity IoC

I include the Unity.Mvc and Unity.AspNet.WebApi bootstrappers which provide the UnityMvcActivator.cs and UnityWebApiActivator.cs files. I uncomment the lines to get the per request lifetime object management.

// UnityMvcActivator.cs
   // TODO: Uncomment if you want to use PerRequestLifetimeManager

// UnityWebApiActivator.cs
   // Use UnityHierarchicalDependencyResolver if you want to use a new child container for each IHttpController resolution.
   var resolver = new UnityHierarchicalDependencyResolver(UnityConfig.GetConfiguredContainer());

And finally, register your types with the container in UnityConfig.cs.

public static RegisterTypes(IUnityContainer container)
    container.RegisterType<IMovieDbContext, MovieDbContext>(new PerRequestLifetimeManager(),
        new InjectionConstructor("name=MovieDbConnection");
    container.RegisterType<IMovieService, MovieService>(new PerRequestLifetimeManager());

Now I have a testable application without a hard dependency on the database. I still need the EntityFramework reference in the Web project but my controllers don’t really know that.


Angular Sortable Dynamic Collection

Here’s an example of a sortable (ui-sortable) on a dynamic collection that I’ve worked out. I’ve wrapped this in a custom directive for a collection of widgets that can be re-ordered.

See the Plnkr working example.

Screen Shot

It uses Angular, Bootstrap and ui-sortable. Unfortunately, there is a dependency on jQuery UI Sortable but I don’t see any problems with this example.


Custom directive

<widget-container class="widget-container"></widget-container>

Directive Template

This is the basic template with the important bits (most of the styling removed). There’s a second directive widget-item embedded to help with the child (collection) items.

<div class="widget-container">
    <button ng-click="widgetContainerCtrl.add()">Add Widget</button>
    <div ui-sortable="widgetContainerCtrl.sortableOptions" ng-model="widgetContainerCtrl.widgets">
      <div widget-item ng-repeat="widget in widgetContainerCtrl.widgets"
        data-id="{{widget.id}}" data-pos="{{widget.pos}}">
        <span class="handle">
          <i class="glyphicon glyphicon-move"></i>
        <button ng-click="widgetContainerCtrl.remove(widget)">
          <i class="glyphicon glyphicon-trash"></i>
        <span>I'm the widget, gotta Love me!</span>

We’ve got to be careful with the DOM structure to satisfy ui-sortable — the ng-repeat needs to be directly below ui-sortable.

Directive JavaScript

  var app = angular.module("app", ["ui.sortable"]);
  app.directive("widgetContainer", [WidgetContainer]);
  function WidgetContainer() {
    return {
      restrict: "E",
      replace: true,
      templateUrl: "widgetContainer.html",
      controller: "WidgetContainerController as widgetContainerCtrl",
      scope: { },
      link: function(scope, element, attrs, ctrl) { }
  app.controller("WidgetContainerController", ["$scope", "$timeout", WidgetContainerController]);
  function WidgetContainerController($scope, $timeout) {
    var _this = this;
    this.$scope = $scope;
    this.$timeout = $timeout;
    this.widgets = [];
    this.sortableOptions = {
      handle: "< .handle",
      update: function(event, ui) {

  WidgetContainerController.prototype.add = function() {
    // this.widgets.push()
  WidgetContainerController.prototype.remove = function(widget) {
    // this.widgets.splice()
  WidgetContainerController.prototype.reorder = function() {
    // reassign widget.pos

Here’s the child directive:

  app.directive("widgetItem", [WidgetItem]);
  function WidgetItem() {
    return {
      restrict: "A",
      scope: {
        widget: "=";
      controller: "WidgetItemController as widgetItemCtrl",
      link: function(scope, element, attrs, ctrl) { }
  app.controller("WidgetItemController", ["$scope", WidgetItemController]);
  function WidgetItemController($scope) {
    this.widget = $scope.widget;
  WidgetItem.prototype.doSomething = function() { }

Datepicker With Bootstrap Icon

This is an update to a previous a post jQuery Datepicker With Bootstrap Icon but instead of the jQuery UI datepicker we will be using a Bootstrap datepicker.

The problem again is we want to be able to click on an icon to trigger the datepicker without having to write any javascript. The idea is the same as in the previous solutionUse the label’s for attribute to trigger the date’s input field.

Here is what we want the control to look like:



<div class="input-group">
    <label class="input-group-btn" for="date-fld">
        <span class="btn btn-default">
            <span class="glyphicon glyphicon-calendar"></span>
    <input type="text" class="form-control date-input" id="date-fld" />

Some things to note:

  1. We are using the Button Addon .input-group-btn instead of the slightly simpler markup for .input-group-addon. This will give the user better UI hints when the cursor is over the icon.
  2. The <button> has been changed to a <span>. Without this change the datepicker is not triggered. You could, instead, use the button and nest a label within the button but this does not render nicely.

For completeness here is the javascript:

    // options

A working example on jsFiddle.

Libraries in this article:
  1. Bootstrap 3.2.0
  2. https://github.com/eternicode/bootstrap-datepicker

MVC Bootstrap Input Group Button Space

Recently, I’ve fired-up a new MVC5 website with the default template. I’m looking to use the Bootstrap input button group but instead of the controls flush against each other I see a large gap between the two elements.

Here is what I’m expecting:


Here is what I get instead:


Here is the HTML markup:

<div class="row">
    <div class="col-md-4">
        <h3>Bootstrap Input Group</h3>
        <div class="input-group">
            <input type="text" class="form-control" />
            <span class="input-group-btn">
                <button class="btn btn-primary">OK</button>

The Problem

It turns out the Visual Studio’s MVC template Site.css stylesheet is causing problems here.

/* Set width on the form input elements since they're 100% wide by default */
textarea {
    max-width: 280px;

The Solution

Remove the max-width and the space between the elements disappear.

Getting The Solution

It would be helpful to share how I solved this issue — For experienced developers this is probably common knowledge.

In this case I used the browser’s debugger tools to inspect the page elements: On the rendered page in the browser, hover the mouse pointer over the input box then Right-ClickInspect Element.


Chrome’s Developer Tools gives you a screen like the one above. Using this you can examine which CSS rules are applied to a specific element and it also tells you which file the rule comes from (site.css, line 20).

The process on Firefox and Internet Explorer is almost exactly the same as with Chrome.

Frameworks and libraries in this article:
  1. ASP.NET MVC 5.1.2
  2. Twitter Bootstrap 3.1.1

Missing .Less Files with Visual Studio 2010 Deployment Package

Recently, I deployed a Visual Studio 2010 web site and was perplexed by the omission of my .less files from the deployment package. What stumped me was my other projects (in VS2012) deployed .less files without any issues.

The solution is to mark the file’s Build Action as Content in the file Properties in Visual Studio. By default Visual Studio 2010 does not recognize .less files.

  1. View → Solution Explorer
  2. Right-click on the .less file → Properties
  3. Change Build Action to Content

file properties

Visual Studio 2012 does not have this problem. One of the common web tools plugins probably accounts for .less files.

Unit of Work and Repository Pattern with Unity Dependency Injection

May 20, 2017 — My new preferred implementation.

Here’s my implementation of a Unit of Work and Repository pattern for ASP.NET MVC with Unity Dependency Injection.

The following example touches on several debatable issues. It is not the intent of this post to contribute to the debate, rather, as an academic or mental exercise to learn more about the patterns and issues. It should not be taken as a recommendation for or against the patterns presented below.

Package and Framework Versions in this article:
  1. MVC4
  2. Entity Framework 5
  3. Unity 3
  4. Unity.MVC3

Unit of Work

public interface IUnitOfWork : IDisposable
    MovieContext DbContext { get; }
    int Save();

public class UnitOfWork : IUnitOfWork
    protected string ConnectionString;
    private MovieContext context;

    public UnitOfWork(string connectionString)
        this.ConnectionString = connectionString;

    public MovieContext DbContext
            if (context == null)
                context = new MovieContext(ConnectionString);
            return context;

    public int Save()
        return context.SaveChanges();

    public void Dispose(bool disposing)
        if (disposing)
            if (context != null)
                context = null;

    public void Dispose()


Generic repositories are presented here but often I’ll extend GenericRepository to provide a more specific or restricted API.

public interface IGenericRepository<TEntity> where TEntity : class
    IQueryable<TEntity> GetAll();
    IQueryable<TEntity> FindBy(Expression<Func<TEntity, bool>> predicate);
    TEntity Add(TEntity entity);
    void Delete(TEntity entity);
    void Update(TEntity entity);

public class GenericRepository<TEntity> :
    IGenericRepository<TEntity> where TEntity : class
    protected MovieContext DbContext;

    public GenericRepository(IUnitOfWork unitOfWork)
        this.DbContext = unitOfWork.DbContext;

    public IQueryable<TEntity> GetAll()
        IQueryable<TEntity> query = this.DbContext.Set<TEntity>();
        return query;

    public IQueryable<TEntity> FindBy(Expression<Func<TEntity, bool>> predicate)
        IQueryable<TEntity> query = this.DbContext.Set<TEntity>().Where(predicate);
        return query;


The service layer keeps much of the business logic out of the controllers and provides a convenient place to put the Entity → model projections.

public interface IMovieService, IDisposable
    IEnumerable<MovieDTO> GetMovies(MovieSearchCriteria searchCriteria);
    IEnumerable<MovieDTO> GetRecommendedMovies(MovieSelectionCriteria criteria);

public class MovieService : IMovieService
    private IUnitOfWork unitOfWork;
    private IGenericRepository<Movie> movieRepository;
    private IGenericRepository<Genre> genreRepository;

    public MovieService(IUnitOfWork unitOfWork,
                        IGenericRepository<Movie> movieRepository,
                        IGenericRepository<Genre> genreRepository)
        this.unitOfWork = unitOfWork;
        this.movieRepository = movieRepository;
        this.genreRepository = genreRepository;

    public IEnumerable<MovieDTO> GetMovies(MovieSearchCriteria searchCriteria)
        var movies = movieRepository.FindBy(m => m.Year == searchCriteria.Year)
            .Select(p => new MovieDTO { Title = p.Title, Year = p.Year, ... }).ToList();
        return movies;


    public void Dispose()

Unity Config

Register everything with Unity. A single line of code registers GenericRepository for all Entity types. Specific repositories, if defined, will also get registered here. Unity.MVC3 takes care of the MVC controllers so they are not registered here.

public static IUnityContainer BuildUnityContainer(string connectionString)
    var container = new UnityContainer();
    container.RegisterType<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager(),
        new InjectionConstructor(connectionString));
    container.RegisterType(typeof(IGenericRepository<>), typeof(GenericRepository<>));
    container.RegisterType<IMovieService, MovieService>();
    return container;

The Microsoft.Practices.Unity.HierarchialLifetimeManager provides:

  1. A Dispose() call after each request
  2. The same DbContext instance per request


public class MovieController
    private IMovieService movieService;

    public MovieController(IMovieService movieService)
        this.movieService = movieService;
And that’s it.

jQuery Datepicker With Bootstrap Icon

Update (2014-08-16):
Not using jQuery UI datepicker? See Datepicker With Bootstrap Icon with eternicode’s Bootstrap-datepicker and Bootstrap 3.

The Problem

I recently needed to use the jQuery UI Datepicker but I also wanted to use Bootstrap’s calendar icon. Simple enough, I thought, the datepicker allows me to specify an icon image. Unfortunately, the built-in datepicker option inserts an img tag and it’s not so easy to add a CSS class needed to use a sprite instead.

Continue reading “jQuery Datepicker With Bootstrap Icon”