1

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://learn.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?

1
  • 1
    A word of caution, doc.microsoft.com is not the best place to learn patterns and practices. It is reference documentation, and usually does the bare minimum to demonstrate usage. Commented Aug 19, 2022 at 8:21

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Well i use the DBContext in the repository classes I don't do it manually it's just that i do it in a separate class than services. I just don't like db transactions in a service class. Also how come the connection is made in each service class instead of once in the startup class like this : 'services.AddDbContext<AuXDbContext>(optBuilder => optBuilder .UseLazyLoadingProxies() .UseSqlServer(connectionString) );'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.