Why use Repository Pattern or please explain it to me? - c#

I am learning repository pattern and was reading Repository Pattern with Entity Framework 4.1 and Code First
and Generic Repository Pattern - Entity Framework, ASP.NET MVC and Unit Testing Triangle
about how they implement the repository pattern with Entity Framework.
Saying
•Hide EF from upper layer
•Make code better testable
Make code better testable I do understand, but why hide EF from upper layer?
Looking at their implementation, it seems just wrap the entity framework with a generic method for query the entity framework. Actually what's the reason for doing this?
I am assuming is for
Loose coupling (that's why hide EF from upper layer?)
Avoid repeat writting same LINQ statement for same query
Am I understand this correctly?
If I write a DataAccessLayer which is a class have methods
QueryFooObject(int id)
{
..//query foo from entity framework
}
AddFooObject(Foo obj)
{
.. //add foo to entity framework
}
......
QueryBarObject(int id)
{
..
}
AddBarObject(Bar obj)
{
...
}
Is that also a Repository Pattern?
Explaination for dummy will be great :)

I don't think you should.
The Entity Framework is already an abstraction layer over your database. The context uses the unit of work pattern and each DBSet is a repository. Adding a Repository pattern on top of this distances you from the features of your ORM.
I talked about this in my blog post:
http://www.nogginbox.co.uk/blog/do-we-need-the-repository-pattern
The main reason adding your own repository implementation is so that you can use dependency injection and make your code more testable.
EF is not very testable out of the box, but it's quite easy to make a mockable version of the EF data context with an interface that can be injected.
I talked about that here:
http://www.nogginbox.co.uk/blog/mocking-entity-framework-data-context
If we don't need the repository pattern to make EF testable then I don't think we need it at all.

This picture makes it easy to understand

One thing is to increase testability and have a loose coupling to underlying persistance technology. But you will also have one repository per aggregate root object (eg. an order can be an aggregate root, which also have order lines (which are not aggregate root), to make domain object persistance more generic.
It's also makes it much easier to manage objects, because when you save an order, it will also save your child items (which can be order lines).

It's also an advantage to keep your queries in a central place; otherwise your queries are scattered around and are harder to maintain.
And the first point you mention: "To hide EF" is a good thing! For instance, saving logic can be hard to implement. There are multiple strategies that apply best in different scenarios. Especially when it comes to saving entities which also have changes in related entities.
Using repositories (in combination with UnitOfWork) can centralize this logic too.
Here are some videos with a nice explanation.

Repository systems are good for testing.
One reason being that you can use Dependency Injection.
Basically you create an interface for your repository, and you reference the interface for it when you are making the object. Then you can later make a fake object (using moq for instance) which implements that interface. Using something like ninject you can then bind the proper type to that interface. Boom you've just taken a dependence out of the equation and replaced it with something testable.
The idea is to be able to easily swap out implementations of objects for testing purposes
Hope that makes sense.

The same reason you don't hard code file paths in your app: loose coupling and encapsulation. Imagine an app with hard coded references to "c:\windows\fonts" and the problems that can cause. You shouldn't hard code references to paths so why should you hard code references to your persistence layer? Hide your paths behind config settings (or special folders or whatever your os supports) and hide your persistence behind a repository. It will be much easier to unit test, deploy to other environments, swap implementations, and reason about your domain objects if the persistence concerns are hidden behind a repository.

When you are designing your repository classes to look alike domain object, to provide same data context to all the repositories and facilitating the implementation of unit of work, repository pattern makes sense. please find below some contrived example.
class StudenRepository
{
dbcontext ctx;
StundentRepository(dbcontext ctx)
{
this.ctx=ctx;
}
public void EnrollCourse(int courseId)
{
this.ctx.Students.Add(new Course(){CourseId=courseId});
}
}
class TeacherRepository
{
dbcontext ctx;
TeacherRepository(dbcontext ctx)
{
this.ctx=ctx;
}
public void EngageCourse(int courseId)
{
this.ctx.Teachers.Add(new Course(){CourseId=courseId});
}
}
public class MyunitOfWork
{
dbcontext ctx;
private StudentRepository _studentRepository;
private TeacherRepository _teacherRepository;
public MyunitOfWork(dbcontext ctx)
{
this.ctx=ctx;
}
public StudentRepository StundetRepository
{
get
{
if(_studentRepository==null)
_stundentRepository=new StundetRepository(this.ctx);
return _stundentRepository;
}
}
public TeacherRepository TeacherRepository
{
get
{
if(_teacherRepository==null)
_teacherRepository=new TeacherRepository (this.ctx);
return _teacherRepository;
}
}
public void Commit()
{
this.ctx.SaveChanges();
}
}
//some controller method
public void Register(int courseId)
{
using(var uw=new MyunitOfWork(new context())
{
uw.StudentRepository.EnrollCourse(courseId);
uw.TeacherRepository.EngageCourse(courseId);
uw.Commit();
}
}

I know it is bad provide links in answer here, however wanted to share the video which explains various advantages of Repository Pattern when using it with Entity framework. Below is the link of youtube.
https://www.youtube.com/watch?v=rtXpYpZdOzM
It also provides details about how to implement Repository pattern properly.

Related

Correct implementation of UnitOfWork and Repository pattern in Entity Framework

I am trying to figure out how to correctly implement UoW and Repository pattern with Entity Framework. I saw a lot of post against it but it still seems like the right way to go.
I am trying to do it according to this blog post. The last thing I am trying to figure out is how to inject the Repositories into the UoW but in a way that lets me do it on demand. The number of repositories may grow and so will the constructor then. Furthermore instantiating all of the repositories for an operation that may require only 1 or 2 seems like a waste of resources.
How do I do it in a way that lets me write unit tests fairly easily?
The only way I found out, that lets me inject repositories NOT in the constructor (so they are not all instantiated, even when they are not needed for a particular operation) is by doing it in the getter:
private IGenericRepository<Blog> _blogRepository;
private IGenericRepository<Post> _postRepository;
public UnitOfWork(BloggingContext bloggingContext)
{
_bloggingContext = bloggingContext;
}
public IGenericRepository<Blog> BlogRepository
{
get
{
return _blogRepository = _blogRepository ?? new GenericRepository<Blog>(_bloggingContext);
}
}
However, this approach generates a lot of noise in the code because when I will have 50 repositories I will need 50 props.
You might want to combine the described approach (which I like) with the generic repository approach described here https://cpratt.co/truly-generic-repository/
Given proper implementation of the UoW pattern from the blog post you reference, you won't need the anything but the IReadOnlyRepository from the article - it will provide everything you need for the repository to be.

Decoupling EF6 from its custom Api

I would like to ask some help regarding Dependency Injection and, I think, architectural approach.
So, I have an ORM layer implemented by EF6 where the objects are described and Ef does what its business, etc. I created a custom library over it, called DatabaseApi and it is mentioned in the title as "Api", where I query the data and map it to datacontract objects. I do it for pure testing purposes. I would like to have the different libraries in my application testable.
I started to implement the code where I inject the DbContext but I don't know how to deal with the usings in this case.
I went through a few blogposts and articles about mocking and EF, especially this one but it is rather about testing EF itself and not about how to decouple it from other libraries. On the other hand, I assume my search keywords were not proper.
Do you know any good and usable tutorials and articles about how to decouple entity framework from other libraries?
Thanks in advance!
Examples:
I created an empty interface in order to the DbContext can be injectable. It is implemented by the databaseContext.
public interface IDatabase
{
}
public class DatabaseModelContext : DbContext, IDatabase{
public DbSet<TableOne> TableOne { get; set; }
public DbSet<TableTwo> TableTwo { get; set; }
}
In the custom Api library constructor I put together a code to resolve the interface by Unity. I don't know whether it is working or not. I haven't executed yet.
public partial class DatabaseApi : IDatabaseApi {
private readonly IDatabase iDatabase;
private readonly UnityContainer unityContainer;
public DatabaseApi()
{
this.unityContainer = new UnityContainer();
this.unityContainer.RegisterType<IDatabase, DatabaseModelContext>();
this.iDiLibDatabase = this.unityContainer.Resolve<IDiLibDatabase>();
}
}
And here is the problem. Due to the injection I'll have and interface but there are the usings which are important to manage the resource as far as I know. How to do it?
public partial class DatabaseApi : IDatabaseApi
{
public List<SomeDataContract> GetMainStructure()
{
var result = new List<SomeDataContract>();
//this is the old implementation
using (var database = new DatabaseModelContext())
{
//some data manipulation magic... :)
}
return result;
}
If you're okay using linq to objects as a core element of your domain access layer then exposing an IQueryable for access to the entities would work...
public interface IRepository<TEntity>
{
IQueryable<TEntity> AllEntities { get; }
}
With that, you can do your Where, Select, etc. without hard wiring directly to EF. Behind the scenes the IRepository implementations would deal with the EF portions, database connectivity, etc. There's no avoiding coupling the to EF at the data access layer. But you can keep it constrained to just that layer using something like you've started. Just make sure the database contexts used by your IRepository objects are the only objects working with EF.
Put another way: Don't have your IDatabase return entities. Just have it deal with the connections, and you should create another layer for domain object access which takes in an IDatabase. In the example I gave, somehow the IRepository implementations would take in an instance of IDatabase.
So, the solution is using Autofac DI framework. I found interesting questions and answers and two really helpful tutorials. Links below:
How do you reconcile IDisposable and IoC?
Dependency Injection with Autofac
Generic Repository and Unit of Work Pattern, Entity Framework, Unit Testing, Autofac IoC Container and ASP.NET MVC
Autofac homepage

Correct use of Repository and Unit Of Work patterns in ASP.NET MVC

I have been trying to implement a generic repository in MVC with Unit of Work and Dependency Injection with Ninject.
The post I have been following is this one
http://codefizzle.wordpress.com/author/darkey69/
I am not getting anything returned when I try to use the repository in my controllers. I suspect it is because there is nothing that specifically links or injects the EFDbContext and cannot seem to work out how to do this.
If anyone has implemented this and can assist that would be greatly appreciated. I won't re-post my code just yet as it is all contained and explained in the post above.
While, ultimately, I would discourage you from using the UoW/Repository patterns with an ORM like Entity Framework, I can still give you an approach I've toyed with, which may be helpful even in something more appropriate to abstracting your context, like a service.
All the link you posted is doing is using generics so you don't have to actually define separate implementations of IRepository for each particular entity type. However, you still must manually new up an instance of the generic repository for each entity type in your IUnitOfWork implementation and alter the interface itself to include each entity's repository instance if you want to actually be able to work with the interface instead of the actual generic instance. Not only is that cumbersome, but it also violates open-closed on both UnitOfWork<T> and IUnitOfWork, and keeping them in sync with changes is going to be loads of fun, as well (read: sarcasm).
An alternative I've toyed with, though I won't go so far as to recommend it, is to use generic methods instead of generic classes. For example, instead of something like:
public class Repository<T> : IRepository<T>
where T : class
{
...
public IEnumerable<T> GetAll()
{
return _dbSet;
}
}
You might do:
public class Repository : IRepository
{
...
public IEnumerable<T> GetAll<T>()
where T : class
{
return context.Set<T>();
}
}
Which means, you only need to new up one Repository instance, and you can then access any entity type in your context off that:
var repo = new Repository(context);
var foos = repo.GetAll<Foo>();
var bars = repo.GetAll<Bar>();
This, of course, negates the need entirely for a unit of work.
The reason I won't necessarily recommend this approach is that it hasn't been field tested. As I've said, I've toyed around with it personally a bit, and I feel comfortable with it myself. However, I'd very much be interested to hear what other developers think of this approach.

Unit of Work through tiers

I'm refactoring an existing MVC.Net application to include the unit of work pattern to make data management a bit more obvious and straight forward.
The application is currently split into
Presentation/UI (MVC Controllers delivering views OR JsonResults for AngularJS)
Business Logic (Containing well... business logic)
DAL (Repositories and EF)
I'm having a hard time trying to figure out how I need to be structuring dependency injection and UoW passing to keep things sensible and testable.
I'm anticipating something like the following to be an example:
public class SomeMVCController : Controller
{
private readonly IStoreFrontLogic _storeFrontLogic;
public SomeMVCController(IStoreFrontLogic storeFrontLogic)
{
_storeFrontLogic = storeFrontLogic;
var uow = new UnitOfWork(User);
_storeFrontLogic.UnitOfWork = uow;
}
public ActionResult SomeRequest()
{
var myViewModel = _storeFrontLogic.OffersForUser();
return View(myViewModel);
}
}
public class StoreFrontLogic : IStoreFrontLogic
{
public UnitOfWork unitOfWork;
public OffersModel OffersForUser()
{
//some logic taking into account the current user in the uow
var prevOrders = unitOfWork.OrdersRepo.GetUsersOrders();
// special offers logic
return specialOffers;
}
}
Does this seem sensible?
I'm not too keen on the requirement to manually push the uow into my logic classes whenever they're required. Is there a more sensible way?
As I said above, this is hard to answer without a specific question or specific domain model but I'll give it a shot.
My understanding of such things is focused pretty heavily through a Domain Driven Design lens.
First of, you should read this series of papers on effective aggregate design. The fact that you need units of work and to do queries from inside your domain classes implies that your model needs work.
Some other thoughts on UOW - having uow produce your repositories is good, but I think you will likely start hitting lots of difficulties with implementation. UoW is super useful in small targeted areas but is very difficult to implement across an entire application. What for example happens when you save? Can you never use EF directly? Is everything thread safe? You might want to simplify what you are trying to achieve.
In your example uow can be scoped to the HttpRequest. Many IoC containers (eg Structuremap) provide a simple way to configure this. You can then have a post-action filter (or even better an OWIN module) to attempt the commit (what happens if there are errors is yet another implementation difficulty to deal with). This will eliminate a lot of the property-assignment nonsense
I'm not sure what type of object is your StoreFrontLogic. It doesn't seem like a domain entity but it contains significant business logic. It could be something similar to a transaction script, but in that case the uow should be fully internal to it.
Is it a stateless service? In that case everything that method uses - orders for user included - should be passed in via a parameter.
If, on the other hand it's an entity then it shouldn't access the database at all, it should already have all orders for the user. Purposeful database denormalization can help quite a bit here.
At the very least pass uow as a parameter to OffersForUser rather than expecting for a property to be set.

Trying to simplify our repository pattern

Currently we have implemented a repository pattern at work. All our repositories sit behind their own interfaces and are mapped via Ninject. Our project is quite large and there are a couple quirks with this pattern I'm trying to solve.
First, there are some controllers where we need upwards of 10 to 15 repositories all in the same controller. The constructor gets rather ugly when asking for so many repositories. The second quirk reveals itself after you call methods on multiple repositories. After doing work with multiple repositories we need to call the SaveChanges method, but which repository should we call it on? Every repository has one. All repositories have the same instance of the Entity Framework data context injected so picking any random repository to call save on will work. It just seems so messy.
I looked up the "Unit Of Work" pattern and came up with a solution that I think solves both problems, but I'm not 100% confident in this solution. I created a class called DataBucket.
// Slimmed down for readability
public class DataBucket
{
private DataContext _dataContext;
public IReportsRepository ReportRepository { get; set; }
public IEmployeeRepository EmployeeRepository { get; set; }
public IDashboardRepository DashboardRepository { get; set; }
public DataBucket(DataContext dataContext,
IReportsRepository reportsRepository,
IEmployeeRepository employeeRepository,
IDashboardRepository dashboardRepository)
{
_dataContext = dataContext;
this.ReportRepository = reportsRepository;
this.EmployeeRepository = employeeRepository;
this.DashboardRepository = dashboardRepository;
}
public void SaveChanges()
{
_dataContext.SaveChanges();
}
}
This appears to solve both issues. There is now only one SaveChanges method on the data bucket itself and you only inject one object, the data bucket. You then access all the repositories as properties. The data bucket would be a little messy looking since it would be accepting ALL (easily 50 or more) of our repositories in its constructor.
The process of adding a new repository would now include: creating the interface, creating the repository, mapping the interface and repository in Ninject, and adding a property to the data bucket and populating it.
I did think of an alternative to this that would eliminate a step from above.
public class DataBucket
{
private DataContext _dataContext;
public IReportsRepository ReportRepository { get; set; }
public IEmployeeRepository EmployeeRepository { get; set; }
public IDashboardRepository DashboardRepository { get; set; }
public DataBucket(DataContext dataContext)
{
_dataContext = dataContext;
this.ReportRepository = new ReportsRepository(dataContext);
this.EmployeeRepository = new EmployeeRepository(dataContext);
this.DashboardRepository = new DashboardRepository(dataContext);
}
public void SaveChanges()
{
_dataContext.SaveChanges();
}
}
This one pretty much eliminates all the repository mappings in Ninject because they are all instantiated in the data bucket. So now the steps to adding a new repository include: Create interface, create repository, add property to data bucket and instantiate.
Can you see any flaws with this model? On the surface it seems much more convenient to consume our repositories in this way. Is this a problem that has been addressed before? If so, what is the most common and/or most efficient approach to this issue?
First, there are some controllers where we need upwards of 10 to 15 repositories all in the same controller.
Say hello to Abstract factory pattern. Instead of registering all repositories in Ninject and injecting them to controllers register just single implementation of the factory which will be able to provide any repository you need - you can even create them lazily only if the controller really needs them. Than inject the factory to controller.
Yes it also has some disadvantages - you are giving controller permission to get any repository. Is it problem for you? You can always create multiple factories for some sub systems if you need or simply expose multiple factory interfaces on single implementation. It still doesn't cover all cases but it is better than passing 15 parameters to constructor. Btw. are you sure those controllers should not be split?
Note: This is not Service provider anti-pattern.
After doing work with multiple repositories we need to call the SaveChanges method, but which repository should we call it on?
Say hello to Unit of Work pattern. Unit of Work is logical transaction in your application. It persists all changes from logical transaction together. Repository should not be responsible for persisting changes - the unit of work should be. Somebody mentioned that DbContext is implementation of Repository pattern. It is not. It is implementation of Unit of Work pattern and DbSet is implementation of Repository pattern.
What you need is central class holding the instance of the context. The context will be also passed to repositories because they need it to retrieve data but only the central class (unit of work) will offer saving changes. It can also handle database transaction if you for example need to change isolation level.
Where should be unit of work handled? That depends where your logical operation is orchestrated. If the operation is orchestrated directly in controller's actions you need to have unit of work in the action as well and call SaveChanges once all modifications are done.
If you don't care about separation of concerns too much you can even combine unit of work and factory into single class. That brings us to your DataBucket.
I think you are absolutely right to use the Unit of Work pattern in this case. Not only does this prevent you from needing a SaveChanges method on every repository, it provides you a nice way to handle transactions from within code rather than in your database itself. I included a Rollback method with my UOW so that if there was an exception I could undo any of the changes the operation had already made on my DataContext.
One thing you could do to prevent weird dependency issues would be to group related repositories on their own Unit of Work, rather than having one big DataBucket that holds every Repository you have (if that was your intent). Each UOW would only need to be accessible at the same level as the repositories it contained, and other repositories should probably not depend on other UOWs themselves (your repositories shouldn't need to use other repositories).
If wanted to be an even bigger purist of the pattern, you could also structure your UOWs to represent just that, a single Unit of Work. You define them to represent a specific operation in your domain, and provide it with the repositories required to complete that operation. Individual repositories could exist on more than one UOW, if it made sense to be used by more than one operation in your domain.
For example, a PlaceCustomerOrderUnitOfWork may need a CustomerRepository, OrderRepository, BillingRepository, and a ShippingRepository
An CreateCustomerUnitOfWork may need just a CustomerRepository. Either way, you can easily pass that dependency around to its consumers, more fine grained interfaces for your UOW can help target your testing and reduce the effort to create a mock.
The notion of every repository having a SaveChanges is flawed because calling it saves everything. It is not possible to modify part of a DataContext, you always save everything. So a central DataContext holder class is a good idea.
Alternatively, you could have a repository with generic methods that can operate on any entity type (GetTable<T>, Query<T>, ...). That would get rid of all those classes and merge them into one (basically, only DataBucket remains).
It might even be the case that you don't need repositories at all: You can inject the DataContext itself! The DataContext by itself is a repository and a full fledged data access layer. It doesn't lend itself to mocking though.
If you can do this depends on what you need the "repository" do provide.
The only issue with having that DataBucket class would be that this class needs to know about all entities and all repositories. So it sits very high in the software stack (at the top). At the same time it is being used by basically everything so it sits at the bottom, too. Wait! That is a dependency cycle over the whole codebase.
This means that everything using it and everything being used by it must sit in the same assembly.
What I have done in the past was to create child injection containers (I was using Unity) and register a data context with a ContainerControlledLifetime. So that when the repositories are instantiated, they always have the same data context injected into them. I then hang on to that data context and when my "Unit of Work" is complete, I call DataContext.SaveChanges() flushing all the changes out to the database.
This has some other advantages such as (with EF) some local caching, such that if more than one repository needs to get the same entity, only the first repository actually causes a database round trip.
It's also a nice way to "batch up" the changes and make sure they execute as a single atomic transaction.

Categories

Resources