'How to use Unit of Work in Domain Layer
I'm trying to use the Unit of work pattern in My Service classes.
I have my CompanyService class
public class CompanyService: ICompanyService
{
private readonly ICompanyRepository _companyRepository;
public CompanyService(ICompanyRepository companyRepository)
{
_companyRepository = companyRepository;
}
public void CreateCompany(Company company)
{
_companyRepository.Add(company);
//I want to have unit of work commit here!!!
//unitofwork.commit();
}
public void UpdateCompany(Company company)
{ etc...}
How can i inject an instance of an UnitOfWork In my ServiceClass if my IUnitOfWork is in My Data Layer, and not in my Domain Layer? Should i have an IUnitOfWork in my Domain Layer? I just think this doesn't sound right...
Solution 1:[1]
Should i have an IUnitOfWork in my Domain Layer?
If your Domain Layer needs it, then the answer is definitely: Yes.
The Domain Layer should contains everything that it needs to work. The only thing you need to keep in mind is that this layer should not reference any external libraries, it should not be tied to any technical specific implementation.
Your IRepository or IUnitOfWork's concrete implementations will be somewhere in an Infrastructure/Data Layer where you can reference whatever framework you want (Entity Framework, ...)
Have a look at this SO answer where I explain what need to be located in the Domain Layer (it's an Onion architecture related question but it doesn't matter).
And have a look at this SO answer where you'll find a way to implement UnitOfWork and Repository patterns easily.
Solution 2:[2]
You can inject the same instance of your UoW in your data- and domain layer. It's the application service that's responsible for UoW scoping and committing, not the domain service. Also see Unit of Work, Entity Framework and Core Services.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sergey Vyacheslavovich Brunov |
| Solution 2 | Community |
