Setting up a multi layer Application.
A few things to keep in mind:
- The power lays in abstraction, being able to easily replace layers.
- A layer/Project has dependencies which can not have circular dependencies!
say your main project has Db models and controllers, and DataAccessLayer has the services. then the DataAccessLayer needs the models from the main project and the Controller needs the services from the DataAccessLayer and thus creating a circular dependency.
Project structure
A simple abstract setup can be:
- DbModels project (containing only plain simple objects equal to database tables)
- IDataAccess project contain all the interfaces of the DataAcess services. (needs dependency on DbModels)
- DataAccessLayer project, implementation of IDataAccess. dependencies: IDataAccess & DbModels
- Toplayer project: contains the webApi/controllers. Dependencies: IDataAccess,DbModels and an implementation of IDataAccess, in this case DataAccessLayer.
The DataAccessLayer will ofcourse need EntityFramework as a reference. Also the DatabaseContext should be in this project (and the database migrations).
Also make sure to use the DI/IOC container to register and resolve the services.
This will be your setup for a repository project.
what other problems you run into?
why a repository pattern:
Credits to microsoft
As you can see in this image. A repository pattern is made to being able to easily switch Database.
If you are never going to switch database or use unit tests on dataAccess layer, it't basically not worth it to implement a repository pattern. (too much work, vs the benefit)