Skip to content

Update EF Sql Server API#2193

Merged
sebastienros merged 3 commits intomainfrom
sebros/efsqlserver
Feb 14, 2024
Merged

Update EF Sql Server API#2193
sebastienros merged 3 commits intomainfrom
sebros/efsqlserver

Conversation

@sebastienros
Copy link
Copy Markdown
Contributor

@sebastienros sebastienros commented Feb 12, 2024

Microsoft Reviewers: Open in CodeFlow

@ghost ghost added the area-integrations Issues pertaining to Aspire Integrations packages label Feb 12, 2024
Comment on lines +111 to +142
// Resolving DbContext<TContextService> will resolve DbContextOptions<TContextImplementation>.
// We need to replace the DbContextOptions service descriptor to inject more logic. This won't be necessary once
// Aspire targets .NET 9 as EF will respect the calls to services.ConfigureDbContext<TContext>(). c.f. https://github.com/dotnet/efcore/pull/32518

var oldDbContextOptionsDescriptor = builder.Services.FirstOrDefault(sd => sd.ServiceType == typeof(DbContextOptions<TContext>));

if (oldDbContextOptionsDescriptor is null)
{
throw new InvalidOperationException($"DbContext<{typeof(TContext).Name}> was not registered");
}

builder.Services.Remove(oldDbContextOptionsDescriptor);

var dbContextOptionsDescriptor = new ServiceDescriptor(
oldDbContextOptionsDescriptor.ServiceType,
oldDbContextOptionsDescriptor.ServiceKey,
factory: (sp, key) =>
{
var dbContextOptions = oldDbContextOptionsDescriptor.ImplementationFactory?.Invoke(sp) as DbContextOptions<TContext>;

var optionsBuilder = dbContextOptions != null
? new DbContextOptionsBuilder<TContext>(dbContextOptions)
: new DbContextOptionsBuilder<TContext>();

optionsBuilder.UseSqlServer(options => options.EnableRetryOnFailure());

return optionsBuilder.Options;
},
oldDbContextOptionsDescriptor.Lifetime
);

builder.Services.Add(dbContextOptionsDescriptor);
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's extract this into a common method so we don't have to duplicate this logic across all 5 EF components.

@sebastienros sebastienros merged commit a64caa1 into main Feb 14, 2024
@sebastienros sebastienros deleted the sebros/efsqlserver branch February 14, 2024 23:21
@github-actions github-actions bot locked and limited conversation to collaborators Apr 21, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

area-integrations Issues pertaining to Aspire Integrations packages

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants