dotnet / dotnet/efcore

Document that IDbContextFactory<TContext> is not covariant

Open
#30,096 4 comments 0 reactions 0 assignees View on GitHub
area-api-docs customer-reported
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

According to the [official documentation of IDbContextFactory](https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.idbcontextfactory-1?view=efcore-7.0), the TContext parameter should be covariant:

>TContext
The [DbContext](https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext?view=efcore-7.0) type to create.
This type parameter is covariant. That is, you can use either the type you specified or any type that is more derived. For more information about covariance and contravariance, see [Covariance and Contravariance in Generics](https://learn.microsoft.com/en-us/dotnet/standard/generics/covariance-and-contravariance).

However, that is not the case in the [source code](https://github.com/dotnet/efcore/blob/main/src/EFCore/IDbContextFactory.cs#LL15C3-L15C3)
```
public interface IDbContextFactory<[DynamicallyAccessedMembers(DbContext.DynamicallyAccessedMemberTypes)] TContext>
where TContext : DbContext
{
```

Is this just a case of a copy paste issue from the documentation of Entity Framework, where the interface actually _was_ covariant?
Is there a reason why this is not supported in EF core? To me it looks like a textbook example of where covariance should work and enable to dynamically provide derived DbContext implementations with different configurations. For example we are using a derived DbContext in automated tests with certain entities configured slightly differently (e. g. sql server variant columns)

TLDR: The below code should work according to the documentation, and did work in old EF, but does not in EF core
```
IDbContextFactory contextFactory = _serviceProvider.GetRequiredService>();
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.