Search code examples
.netasp.net-coredependency-injectionarchitectureclean-architecture

Clean architecture : why direct reference between Api and Database layers?


It's seems contradictory to the goal of a clean architecture to have the Api project (ex: .Net core Api MVC) require a direct reference to the Database project, in order to inject as a service the DbContext:

services.AddDbContext<IDatabaseService, DatabaseService>();

Layers are supposed to be indepedent and not aware of a specific implementation, in this case the DatabaseService class. I see this approach several tutorials.

I am wondering how this could be improved ? Perhaps a central (core) project layer dedicated to dependency injections ?


Solution

  • IOC is generally how we achieve abstraction and Clean Architecture, all sorts of coupling is totally allowed in your IOC container.

    You are generally correct however in that relying directly on the DbContext instead of something like the Repository Pattern makes things strongly coupled to a database, thus breaking Clean Code. It's a compromise many developers make simply because they feel it's unlikely they will decompose their application and decouple it from it's relevant database.

    They can of course be very wrong, and if they decide their context is too large, and they need to break a piece off into it's own service, they will have some refactoring to do.