EF6 (code first), MVC, Unity, and a service layer without a repository

asp.net asp.net-mvc entity-framework entity-framework-6

Question

My application is using SQL Server 2012, EF6, MVC and Web API.

It's also using a repository and assorted files such as:

DatabaseFactory.cs
Disposable.cs
IDatabaseFactory.cs
IRepository.cs
IUnitOfWork.cs
RepositoryBase.cs
UnitOfWork.cs

We already use a service layer between our controllers and the repository for some complicated business logic. We have no plans EVER to change to a different database and it has been pointed out to me that the recent thinking is that EF6 is a repository so why build another repository on top of it and why have all of the files I have above.

I am starting to think this is a sensible approach.

Does anyone know of any examples out there that implement EF6 without a repository, with a service layer. My search on the web has revealed many complex code examples that seem over complicated for no reason at all.

My problem is also when using a Service Layer then where do I put:

context = new EFDbContext()

In the controller, the service layer or both ? I read that I can do this with dependancy injection. I already use Unity as an IOC but I don't know how I can do this.

1
8
2/17/2014 5:52:43 PM

Popular Answer

Entity Framework IS already a Unit of Work pattern implementation as well as a generic repository implementation (DbContext is the UoW and DbSet is the Generic Repository). And I agree that it's way overkill in most apps to engineer another UoW or Generic Repository on top of them (besides, GenericRepsitory is considered to be an anti-pattern by some).

A Service layer can act as a concrete repository, which has a lot of benefits of encapsulating data logic that is specific to your business needs. If using this, then there is little need to build a repository on top of it (unless you want to be able to change your backend service technology, say from WCF to WebApi or whatever..)

I would put all your data access in your service layer. Don't do data access in your controller. That's leaking your data layer into your UI layer, and that's just poor design. It violates many of the core SOLID concepts.

But you do NOT need an additional UnitOfWork, or other layers beyond that in most cases, unless your apps are very complex and intended to work in multiple environments...

8
2/17/2014 10:12:17 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow