b.logrythmik

{ dependency injection }

Using Policy Injection with ASP.NET MVC and Unity

There are a million and a half articles out there about Policy Injection and the Policy Injection Blocks (from Enterprise Library). Most of them are by my new favorite blogger, David Hayden. If you aren't familiar with Unity, check out these posts first.

The articles span the life-cycle of Unity from before Policy Injection was introduced and some of the actual type names change from article to article, so it wasn't as straight forward as I am going to make it here.

First of all, I didn't want to use a config file - I wanted to configure my policies in the same place I was configuring my dependencies; in the Global.asax code-behind.

It turns out that this is super easy!

Assuming you already have a reference to the Unity library "Microsoft.Practices.Unity", all you need to add is a reference to the "Microsoft.Unity.Interception" library, found in Microsoft Enterprise Library 4.1

You probably already have a place where you are configuring your dependencies:

// Register for Dependency Injection

container.RegisterType<IDataContextProvider, DataContextProvider>();

Now all you need to do is setup the container with an extension that's called 'Interception' then configure each of the Interfaces you want to intercept with Policies. Like so:

// Register for Policy Injection

container.AddNewExtension<Interception>().Configure<Interception>()

    .SetDefaultInterceptorFor<IDataContextProvider>(new TransparentProxyInterceptor());

Now, when you use Unity to resolve your objects, it will detect if any policies are decorated on the interface or the concrete class. If there are policies, Unity creates a transparent proxy object and executes your policies like it does in the Policy Application Blocks. Check out this article to see how to create handlers.

Now you are ready to place your "Policy Attributes" on your classes. Later, I will show you some of my favorite policies I have written for MVC.

A Generic Repository for LinqToSql

In my last article, I showed you a way of creating an interface for the LinqToSql DataContext so that you can mock the actual implementation for unit testing. Well, there is another benifit to creating such an interface. The interface we created, uses LinqToSql's underying generic methods. Using this, we can create a completely generic repository class, to handle all data transactions from our data-layer.

I won't get into the Repository Pattern or Domain Driven Design, because there are too many people out there, WAY smarter than me discussing it in full. I use this pattern mainly for convenience in testing and reducing code, but it is worth reading up on -- it is some great stuff!

First off, there are literally a THOUSAND articles out there talking about the Repository Pattern and quite a few articles discussing implementing this with the LinqToSql DataContext. None of them were quite what I needed, so I present to you, my version with ideas borrowed from this article and this one (both of these concepts are awesome, however they lacked the IDataContext piece so that it can be unit tested.

IDataContext

First, let's assume that you have already followed my last article, and your DataContext implements IDataContext.

public interface IDataContext : IDisposable

{

    IQueryable<TEntity> GetQueryable<TEntity>() where TEntity : class;

    ITable GetEditable<TEntity>() where TEntity : class;

    void Insert<TEntity>(TEntity instance) where TEntity : class;

    void InsertAll<TEntity>(IEnumerable<TEntity> instances) where TEntity : class;

    void Delete<TEntity>(TEntity instance) where TEntity : class;

    void DeleteAll<TEntity>(IEnumerable<TEntity> instances) where TEntity : class;

    void SubmitChanges();

    int ExecuteCommand(string command, params object[] parameters);

    DbConnection Connection { get; }

}

Implemented in your DataContext

partial class SampleDataContext : IDataContext

{

    public virtual IQueryable<TEntity> GetQueryable<TEntity>() where TEntity : class

    {

        return this.GetTable<TEntity>();

    }

 

    public virtual ITable GetEditable<TEntity>() where TEntity : class

    {

        return this.GetTable<TEntity>();

    }

 

    public void Insert<TEntity>(TEntity instance) where TEntity : class

    {

        this.GetTable<TEntity>().InsertOnSubmit(instance);

    }

 

    public void InsertAll<TEntity>(IEnumerable<TEntity> instances) where TEntity : class

    {

        this.GetTable<TEntity>().InsertAllOnSubmit(instances);

    }

 

    public void Delete<TEntity>(TEntity instance) where TEntity : class

    {

        this.GetTable<TEntity>().DeleteOnSubmit(instance);

    }

 

    public void DeleteAll<TEntity>(IEnumerable<TEntity> instances) where TEntity : class

    {

        this.GetTable<TEntity>().DeleteAllOnSubmit(instances);

    }

}

IDataRepository

Once implemented, let's create our interface for the IDataRepository. We will need the basic data operations: List, GetAddDelete and SubmitChanges.

public interface IDataRepository<T>

        where T : class

{

    IQueryable<T> List();

    T Get(int id);

    T Get(Expression<Func<T, bool>> selector);

    void Add(T instance);

    void Delete(T instance);

    void SubmitChanges();

}

DataRepository<T>

Ah, moving on to the actual implementation... Use IDataContext to implement the repository methods.

public class DataRepository<T> : IDataRepository<T>

        where T : class

{

    private readonly IDataContext _DataContext;

 

    public DataRepository(IDataContext dataContext)

    {

        _DataContext = dataContext;

    }

 

    public IQueryable<T> List()

    {

        return _DataContext.GetQueryable<T>();

    }

 

    public T Get(int id)

    {

        var itemParameter = Expression.Parameter(typeof(T), "item");

 

        var whereExpression = Expression.Lambda<Func<T, bool>>

            (

            Expression.Equal(

                Expression.Property(

                    itemParameter,

                    typeof(T).GetPrimaryKey().Name

                    ),

                Expression.Constant(id)

                ),

            new[] { itemParameter }

            );

 

        return _DataContext.GetQueryable<T>().SingleOrDefault(whereExpression);

    }

 

    public T Get(Expression<Func<T, bool>> selector)

    {

        return _DataContext.GetQueryable<T>().SingleOrDefault(selector);

    }

 

    public void Add(T instance)

    {

        _DataContext.GetEditable<T>().InsertOnSubmit(instance);

    }

 

    public void Delete(T instance)

    {

        _DataContext.GetEditable<T>().DeleteOnSubmit(instance);

    }

 

    public void SubmitChanges()

    {

        _DataContext.SubmitChanges();

    }

}

This class uses Dependency Injection and accesses the DataContext as IDataContext. This allows us to create unit tests for this class with a mocked data-context.

There are two Get methods, both of which pass a Where expression down to the Linq extensions. The first attempts to build an expression manually. This is assuming that you use int as your IDs. If you don't you can always update the code to fit your needs. GetPrimaryKey() is an extension method written by the genius, Mike Hadlow over here. It's awesome, and I included it down below.

Both return a single instance from the DataContext, but the Get(Expression<Func<T,bool>> selector) function allows a more complex lookup (for complex identities or whatever). It's passed as an expression, just like the "Where()" function, in the Linq extensions.

Sample Usage

So what does this buy us? Well, with this simple generic class we suddenly have a full, strongly-typed repository layer for each object in the DataContext.

Check it out:

public class Controller

{

    readonly IDataRepository<User> _UserRepository;

    readonly IDataRepository<Car> _CarRepository;

 

    // Go ahead and use Dependency Injection -- you know you wanna.

    public Controller(IDataRepository<User> userRepository, IDataRepository<Car> carRepository)

    {

        // You can now declare and use "specific" repositories for your Linq objects.

 

        _UserRepository = userRepository;

        _CarRepository = carRepository;

    }

 

    public void DoSomething()

    {

        // Basic get by ID

        var car = _CarRepository.Get(1);

 

        // Complex selector

        var differentCar = _CarRepository.Get(c => c.Name == "Ford");

 

        // Basic list

        var listOfUsers = _UserRepository.List();

 

        // List, with filters

        var filteredUsers = _UserRepository.List()

            .Where(u => u.Name.StartsWith("T"));

 

        // Add

        _UserRepository.Add(new User { Name = "Fred"});

        _UserRepository.SubmitChanges();

 

        // Update

        var editableUser = _UserRepository.Get(1);

        editableUser.Name = "New Name";

        _UserRepository.SubmitChanges();

    }

 

}

Obviously, you can only create a Repository<T> for a class in your context. Otherwise, you would see an epic exception.

Another great thing about this pattern is it's benifits with code-coverage. You can create unit tests for each of these methods and in effect cover your entire data-layer. Not to mention the value in having less code laying around.

OH, and here's that extension method:

public static PropertyInfo GetPrimaryKey(this Type entityType)

{

    foreach (PropertyInfo property in entityType.GetProperties())

    {

        ColumnAttribute[] attributes = (ColumnAttribute[])property.GetCustomAttributes(typeof(ColumnAttribute), true);

        if (attributes.Length == 1)

        {

            ColumnAttribute columnAttribute = attributes[0];

            if (columnAttribute.IsPrimaryKey)

            {

                if (property.PropertyType != typeof(int))

                {

                    throw new ApplicationException(string.Format(

                        "Primary key, '{0}', of type '{1}' is not int", property.Name, entityType));

                }

                return property;

            }

        }

    }

    throw new ApplicationException(string.Format(

        "No primary key defined for type {0}", entityType.Name));

}

 

RepositorySample.zip (9.40 kb)

IDataContext - Using an Interface for the LinqToSql DataContext

As you know, I have recently become a huge fan of the Dependency Injection (DI) and Inversion of Control (IoC) patterns, but was stumped when trying to implement this pattern down to my data layer. I LOVE LinqToSQL, but I wasn't sure how I could make the Linq DataContext an abstract interface. I stumbled upon a great article discussing How to make the DataContext "Unit Testable". From this, I boiled down a version of an interface that was easy to implement in the DataContext.

An Interface for the DataContext: IDataContext

LinqToSql exposes Sql Server tables as theunmockable Table which is a sealed class. But LinqToSql namespace has an interface ITable which the Table type implements and that is easy to mock, also this ITable exposes InsertOnSubmit, InsertAllOnSubmit, DeleteOnSubmit, DeleteAllOnSubmit. So in our interface we exposed the ITable instead of that concrete Table which makes this partial Database class completely unit testable.

public interface IDataContext : IDisposable

{

    IQueryable<TEntity> GetQueryable<TEntity>() where TEntity : class;

 

    ITable GetEditable<TEntity>() where TEntity : class;

 

    void Insert<TEntity>(TEntity instance) where TEntity : class;

 

    void InsertAll<TEntity>(IEnumerable<TEntity> instances) where TEntity : class;

 

    void Delete<TEntity>(TEntity instance) where TEntity : class;

 

    void DeleteAll<TEntity>(IEnumerable<TEntity> instances) where TEntity : class;

 

    void SubmitChanges();

 

    int ExecuteCommand(string command, params object[] parameters);

 

    DbConnection Connection { get; }

}

As you can see, all the basic functions of the DataContext exist for your consuming class.

Implement that Sucker

Now we need to implement this interface in our DataContext. Right-click on your DBML file, and select "View Code".  This creates a partial class file for the DataContext. In it, you can implement the interface.

partial class SomeDataContext: IDataContext

{

    public virtual IQueryable<TEntity> GetQueryable<TEntity>() where TEntity : class

    {

        return this.GetTable<TEntity>();

    }

 

    public virtual ITable GetEditable<TEntity>() where TEntity : class

    {

        return this.GetTable<TEntity>();

    }

 

    public void Insert<TEntity>(TEntity instance) where TEntity : class

    {

        this.GetEditable<TEntity>().InsertOnSubmit(instance);

    }

 

    public void InsertAll<TEntity>(IEnumerable<TEntity> instances) where TEntity : class

    {

        this.GetEditable<TEntity>().InsertAllOnSubmit(instances);

    }

 

    public void Delete<TEntity>(TEntity instance) where TEntity : class

    {

        this.GetEditable<TEntity>().DeleteOnSubmit(instance);

    }

 

    public void DeleteAll<TEntity>(IEnumerable<TEntity> instances) where TEntity : class

    {

        this.GetEditable<TEntity>().DeleteAllOnSubmit(instances);

    }

}

Example Usage

Now, your consuming classes are free to use the DataContext as the Interface "IDataContext" which can be mocked in Unit Tests.

public class SomeController

{

    readonly IDataContext _DataContext;

 

    public SomeController(IDataContext dataContext)

    {

        _DataContext = dataContext;

    }

 

    public void DoSomething()

    {

        var foo = _DataContext.GetQueryable<Foo>()

                 .SingleOrDefault(f => f.FooId == 1);

 

    }

}

Conclusion

This demonstrates how you can make your DataContext an interface that is mockable and could be injected at runtime for DI. In the next article, I will show how you can create a generic repository using the IDataContext.