Thursday, July 28, 2016

Implementing the Repository Pattern in C# with Entity Framework

If you are looking to implement the Repository Pattern in C#, you may find lots and lots and LOTS of conflicting solutions about how to implement the Repository Pattern in your own application.

If you just do a quick search just on MSDN, you will find articles such as the following:

If you look through the examples above, you will see that they offer different solutions to the same Repository Pattern problem.  However, the second example provides the ability to create a Generic Repository which is much more appealing than creating a different repository for each class in your entire data model!

Unfortunately, the MSDN example lacks a definition of a generic interface which GenericRepository implements.  Looking at the code, you can derive your own IRepository interface, but the example still lacks support for a Dependency Injection or IoC container.  As you will readily notice, the example directly requires an implementation of SchoolContext to be created.  The way in which the example gets around direct creation of the SchoolContext is by using a Unit of Work class which handles the creation of this instance.  While the Unit of Work class can be useful in aggregating multiple repositories, it may not make much sense for instances when you simply need a single repository, which is why an IoC container is very useful!

So how exactly do you get Ninject to work in this scenario?

For Ninject, you simply use the following code to inject your SchoolContext instance:

You can simply add the following code to your RegisterServices method inside of your NinjectWebCommon.cs file and this should do the trick for you!

No comments:

Post a Comment