mercredi 11 mai 2022

.NET/C# Unit of work pattern with generic repositories

Im creating unit of work with generic repository, the question is about a performance in two approaches:

First - creating singleton unitofwork instance and whenever getting a request for any repo usage, check if its already created - then use it, or if not - create one:

public class UnitOfWork : IUnitOfWork
{
    public Dictionary<Type, object> _repositories = new();
    private readonly Context _context;

    public UnitOfWork(Context context)
    {
        _context = context;
    }

    public IRepository<T> Repository<T>()
    {
        if (_repositories.ContainsKey(typeof(T)))
            return _repositories[typeof(T)] as IRepository<T>;

        var requestedRepositoryType = new Repository<T>(_context);

        _repositories.TryAdd(typeof(T), requestedRepositoryType);

        return requestedRepositoryType;
    }
}

Second: just simply create unitOfWork as in 99% existing examples with scoped injection like eg here https://medium.com/codex/generic-repository-unit-of-work-patterns-in-net-b830b7fb5668

Im wondering if using my approach wouldnt have better performance because we can just simply use one implementation of unitofwork and repositories (only first use when they are created will cost us). Have anyone more experienced can mayby give me a quick explanation of that topic?

Best regards and thanks in advance.

Aucun commentaire:

Enregistrer un commentaire