0

I've got a design question regarding the asynchronous use of dbcontext in the case of REST web services server. I'm quite "new" to the C# world, I come from a Java background. That is my first C# application

I'm currently developing that server as a backend for an Angular SPA. C# .net 4.5, Web API 2, MVC 5, entity framework 6, Unity for the dependency injection.

I've used that "old" tutorial as a base to start the development of the application : https://www.codeproject.com/Articles/990492/RESTful-Day-sharp-Enterprise-Level-Application#_Toc418969124

The design of that application (and mine too) is the following :

1) Controllers Layer (web services entry points)

2) Business Service Layer (where the business logic lies)

3) Unit of work/repository Layer

I read and learned quite a lot over the last weeks, including lots of articles explaining why the repo/UoW pattern is obsolete since it actually is an abstraction of an abstraction when used with DbContext.

Here is my question:

I would like to implement asynchronous database requests for my application since it is designed to process web services. The problem seems to be that the Entity Framework DbContext object isn't thread-safe. Appears it has to be tightly managed to prevent overlapping. From what I read so far, it seems that the DbContext should be injected in the request scope.

I would like, as much as possible :

1) keep the business logic inside the service layer

2) get rid of the Unit of Work / Repository layer (using the DBContext inside the service layer)

3) Injecting and disposing of correctly the DBContext to use asynchronicity without troubles.

I'm looking for some advises or examples in order to use my DbContext object right in an asynchronous context.

waka
  • 3,362
  • 9
  • 35
  • 54
Sechs
  • 1
  • 3
  • That is a good strategy. You never mention how you are injecting it, that is with what life time. The lifetime scope for the DbContext should be instance per request or instance per owned. **If** that resolves your issue this question might be considered a duplicate of [using a Handler in Web API and having Unity resolve per request](https://stackoverflow.com/a/22576682/1260204) – Igor Oct 02 '17 at 10:35
  • "repo/UoW pattern is obsolete since it actually is an abstraction of an abstraction when used with DbContext." I've also seen a lot of articles that say this but I've seen many articles that say that you should always have a design where there's an abstraction to any framework (EF in this case). "2) get rid of the Unit of Work / Repository layer (using the DBContext inside the service layer)" You will now have a direct dependency to EF in all your services. IMO that is not a good design - EF should be interchangeable without your services ever being touched. – TheRock Oct 07 '17 at 12:16

0 Answers0