IUnitOfWork how to use - best practice

I use EF4.3.1 in .Net4.0 web forms (not MVC!).

I am using the repository template with the IUnitOfWork interface. But I wonder if I follow the best practices, especially since most of the examples I used are based on MVC applications.

I will only say this to a small web application, so this may affect the choice of solution.

Currently, the solution has 3 projects: model, logic and website. The model contains codefirst objects and the IUnitOfWork interface. Logic contains repositories and service levels. The site obviously contains a website, codebehind, etc.

I do not use a third-party injection tool (ninject, etc.). I manually add repositories using IUnitOfWork ie

public BookingRepository (IUnitOfWork unitOfWork)

I do not know what to do with service levels if IUnitOfWork also exists in the Site project or exists only in the Logic and Model layers.

I am currently inserting a repository and unit of work into a service, i.e.

public BookingService (IUnitOfWork unitOfWork, IBookingRepository repository, IAppSettings appSettings)

But this means that commiting (save to db) is done at the site level, but I wonder if it should be done at the service level. It also means that since my IUnitOfWork is declared in my model layer, I also need a link to the Model on my site.

What can I do better? Am I doing something right? lol

+4
source share
1 answer

Dmitry is right. Here is an example of implementing a Unit of Work. The advantage here is that the workflow block coordinates the work of several repositories, using one common database context class, common to all.

This is a good resource to understand how these patterns can be used together. It is valid for developing MVC and web forms. Implement repository and unit of work patterns in an ASP.NET MVC application

public class UnitOfWork : IDisposable { private DbContext _context; private PersonRepository _personRepository; private CompanyRepository _companyRepository; public UnitOfWork(DbContext context) { this._context = context; } public void Commit() { _context.SaveChanges(); } // We lazy-load our repositories... public PersonRepository PersonRepository { get { if (this._personRepository == null) { this._personRepository = new PersonRepository(context); } return _personRepository; } } public CompanyRepository { get { if (this._companyRepository == null) { this._companyRepository = new CompanyRepository(context); } return _companyRepository; } } //IDisposable implementation removed for brevity... } 
+3
source

Source: https://habr.com/ru/post/1403766/


All Articles