aspnet / DependencyInjection

[Archived] Contains common DI abstractions that ASP.NET Core and Entity Framework Core use. Project moved to https://github.com/aspnet/Extensions

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Connection Leak with DI

ConX-Ryan opened this issue · comments

issuelink

services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();
services.AddScoped<DbShardContextFactory>();

 services.AddScoped<ConXDbContext<Guid>>(provider => 
                 provider.GetService<DbShardContextFactory>().CreateShardContext());

 services.AddIdentity<AppUser, IdentityRole>()
                .AddEntityFrameworkStores<ConXDbContext<Guid>>()
                .AddDefaultTokenProviders();

I am using a single tenant config where i need to route to a customer shard based on the request. The DbShardContextFactory does this with help from the HttpContextAccessor.

Because the factory creates the DbContext instead of the DI Container it appears to not be disposing correctly even though defined as Scoped. so the .AddEntityFrameworkStores<ConXDbContext>()
call i believe is the issue

What is the correct pattern here to use the standard ASP.NET Core service collection?

I am having trouble defining the right pattern to use here, we are just migrating and what was previously working in Ninject .InRequestScope() is not the same with the in built DI.

What would be the functional equivalent pattern here?

services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();

This should be a singleton.

As for the other objects..

What is a DbShardContextFactory? How does the ShardDbContext<Guid> relate to the ConXDbContext<Guid>?

How does the ShardDbContext relate to the ConXDbContext?

Sorry that is a typo, they are meant to be the same, i was trying to clean code up for example.

The DbShardContextFactory is responsible for providing a SqlConnection obj to the constructor of the ConXDbContext, it parses the request and maps a connection to a shard from the subdomain, previously it created and returned the new ConXDbContext but reading the ASP.NET Core docs because it wasnt created by the DI container it wont be disposed.

Thanks for your time :)

I inlined the wire up here to avoid going back to the link. What's not getting disposed?

I believe that the .AddEntityFrameworkStores<ConXDbContext<Guid>>() is leading to the connection leak i am experiencing.

other repositories are being disposed in a "Scoped" fashion as expected.

I have resolved this issue by migrating to AutoFac, to use the InstancePerLifetimeScope and constructor resolution as EF needs the design time opts which lead to an ambiguous constructor error, then i am manually closing the connection in the DbShardContextFactory because even though the Dispose method is being called the connection was not closing.

This issue was moved to dotnet/aspnetcore#2335