Home > Blockchain >  No repository classes/layer when designing a Rest API in ASP.NET Core?
No repository classes/layer when designing a Rest API in ASP.NET Core?

Time:08-20

I come from a Java background and when I have designed APIs I have always done all database transactions in repository classes, called on their functionality in my service classes where I do my heavy calculations try/catch and finally presented the results to the controller that checks what kind of result it is and passes it on.

Now I'm building a API in ASP.NET Core 6 and all documentation I read seems to show/say that all DB transactions are made inside the service classes it self. For example here:

https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mongo-app?view=aspnetcore-6.0&tabs=visual-studio

For reference I'm also using a MongoDB. But this feels strange to Initiate a DB connection in each service class and then do DB transactions there as well. Is this correct?

Can I follow the pattern on this page?

CodePudding user response:

In continuation with my comment above, dotnet community is generally moving away from repository pattern in the favor of injecting EF data context directly into service layer.

That serves two purposes, and takes away one degree of freedom.

  1. DbContext already embodies many aspects of the repository pattern through its DbSet<T> properties.
  2. In addition to being mostly a repository of persistent data, it also implements unit of work through SaveChanges[Async]() methods coupled with transactions.
  3. You, however, lose the freedom of testing or mocking your data access queries like you would through a true repository. Unless extra care is taken to abstract away all queries behind their own interfaces whose implementation delegates to the actual DbContext, and which are hence injected into service layer in turn you cannot easily test the data access logic.

You can still create and use repositories which wrap a DbContext instance, but you'll be fighting the functionality it provides and rebuilding all that yourself. Particularly #1 and #2 above.

  • Related