Comments (10)
I like to create a generic method to ask for a repository. Internally it uses the ServiceProvider to inject/return a repository.
Something like this:
public interface IUnitOfWork
{
IRepository<T> Repository<T>() where T : BaseEntity;
int Complete();
}
public class UnitOfWork : IUnitOfWork
{
private readonly SomeDbContext _db;
private readonly IServiceProvider _serviceProvider;
public UnitOfWork(SomeDbContext db, IServiceProvider serviceProvider)
{
_db = db;
_serviceProvider = serviceProvider;
}
public IRepository<T> Repository<T>() where T : BaseEntity
{
return _serviceProvider.GetRequiredService<IRepository<T>>();
}
public int Complete()
{
return _db.SaveChanges();
}
}
I've modified the repository classes to not update the database on add and remove and completely removed the update method. The UnitOfWork
is responsible for these actions.
You can use it like this:
var usersById = new UsersByIdSpecification(new [] { 1, 2, 3 });
var userRepository = unitOfWork.Repository<User>();
var users = userRepository.List(usersById);
users[0].Name = "George";
users[1].Name = "Sally";
userRepository.Remove(users[2]);
unitOfWork.Complete();
from eshoponweb.
Why I like using the UoW pattern:
https://programmingwithmosh.com/entity-framework/common-mistakes-with-the-repository-pattern/
A pattern that goes hand in hand with the repository pattern is the unit of work. With the unit of work, we can re-write that ugly code like this:
orderRepository.Add(order); shippingRepository.Add(shipping); unitOfWork.Complete();Now, either both objects are saved together or none are saved. The database will always be in a consistent state. No need to wrap this block inside a transaction. No need for two separate calls to the Save() method!
Yeah, you could use transactions to have the same effect, but I'm terms of simplicity, this is my preferred solution.
If you don't need this functionality, then don't bother with the pattern. That's my opinion.
from eshoponweb.
@yarrgh shows some good implementation options. As I wrote, I didn't need one in the initial version, so I didn't both adding it to keep things simpler. EF has it built in, but even if it didn't, I'm not using EF's capability because I'm explicitly saving changes on each write event in the repository implementation. In a web/web API app it's often the case that you want to do very small, atomic tasks within a given request, and then return. In this scenario, the need for UoW is the exception-case. In more complex scenarios where you need it, you can create your own UoW implementation or you can create one-off data access methods that perform a group of tasks within a transaction or similar scope.
from eshoponweb.
There was no need in the v1 sample. There may be more complexity that would warrant it in the v2 sample. Is there a specific instance in the sample where you would want to see it, or are you just looking for guidance on how to implement the pattern?
from eshoponweb.
Yes @ardalis , How Can I implement uow design pattern in eShopOnWeb. Whats the best way for implement without compromising the project structure.
from eshoponweb.
Not sure what you mean. If you don't like the UoW knowing about the ServiceProvider, you can always leave that dependency off and remove the repository method. From there you'd just inject your repositories along with the UoW in your controllers/services. Or just inject the repositories into the UoW and expose them as properties.
from eshoponweb.
@yarrgh : by doing this you sacrificed having explicit dependencies
from eshoponweb.
Why do you want to use the UoW pattern? Behind the scenes EF is already using a UoW Pattern (SaveChanges). For some more details you can follow this tutorial: https://cpratt.co/generic-entity-base-class/
However I'm not sure I would recommend this implementation since it would break the idea of DRY(Don't Repeat Yourself) and the SRP (Single Responsibility Principle). But it will help you understand why you don't really need another Unit Of Work Pattern in this case.
from eshoponweb.
@yarrgh No matter what, I agree with you. In ddd, I prefer use UOW to manage repositories to ensure the consistent state of aggregate.
from eshoponweb.
@vertonghenb , EF has UoW built in, but how about other ORM frameworks? ORM tech should separated from upper layer like Repository/Business Logic.
from eshoponweb.
Related Issues (20)
- OBE
- Verify devcontainer for codespaces debugging HOT 6
- Modernize to .NET SDK Containers
- Inconsistent naming of async methods HOT 1
- How to connect to the postgres instance from the host ? HOT 1
- DO NOT USE THIS DIRECTLY
- Cannot Debug BlazerAdmin HOT 1
- Update on Plans for .NET Architecture Samples, Repos, and Organization
- CachedCatalogViewModelService risky? HOT 4
- incorrect about section in github description HOT 1
- Inject IHttpContextAccessor to CatalogContext's constructor will be destoryed when RevokeAuthenticationEvents.cs handle about CatalogContext's data
- The style class prefix "col-xs-*" didnt work in cshtml files. HOT 1
- Changelog for the latest version, updated to .NET 7, is not available in the wiki page HOT 4
- Update to bootstrap 5
- .NET 8 Updates HOT 5
- Facing issue when deploying the application on azure app service HOT 2
- I am not able to deploy the application to Azure from Visual Studio Code HOT 1
- I'm not able to update in memory database HOT 1
- Update NuGet packages to latest versions HOT 1
- Revalidate AZD HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from eshoponweb.