ffernandolima / ef-core-data-access

It's a modern and generic data access structure for .NET and Microsoft.EntityFrameworkCore. It supports UnitOfWork, Repository and QueryBuilder patterns. It also includes auto history utilities, multiple databases support with distributed transactions and databases/tables sharding for some database providers.
MIT License
165 stars 25 forks source link

Pool context #11

Closed FoxTes closed 2 years ago

FoxTes commented 2 years ago

Hello. I really liked your library.

I would like to talk about the outcome. In EF 5 AddPooledDbContextFactory. This allows the pool factory to be used by the context. Is it possible to use it in this library?

ffernandolima commented 2 years ago

Hi!

I'm so glad you liked it.

What's the main purpose of using AddPooledDbContextFactory extension?

According to MS docs, it's recommended for Blazor apps and other situations where the dependency injection scope is not aligned with the context lifetime.

Also, the pooling behaviour can be reached by registering a DbContext through AddDbContextPool extension, so a pooled DbContext instance would be injected into the UnitOfWork once it's created.

If you really want/need to use an IDbContextFactory<TContext>, I think this can be a possible solution:

public class PooledUnitOfWork<T> : UnitOfWork, IUnitOfWork<T> where T : DbContext
{
    #region Ctor

    public PooledUnitOfWork(IDbContextFactory<T> dbContextFactory)
        : base(dbContextFactory?.CreateDbContext())
    { }

    #endregion Ctor
}

DI registering where T is your DbContext:

services.TryAddTransient<IRepositoryFactory<T>, PooledUnitOfWork<T>>();
services.TryAddTransient<IUnitOfWork<T>, PooledUnitOfWork<T>>();

Choose the most appropriated ServiceLifetime for your scenario.

Feel free to go further and test it according to your needs.

FoxTes commented 2 years ago

The use of this extension is related to performance. Thanks to the use of a pool, we reduce allocations.

FoxTes commented 2 years ago

Don't you want to add this extension to your library?

ffernandolima commented 2 years ago

Sure, it can be added to the library anyway.

Have you tested and validated the expected behaviour? Is everything ok?

FoxTes commented 2 years ago

Unfortunately, I have not tested this case. I can't say anything.

ffernandolima commented 2 years ago

Done.