Skip to content

Document that IDbContextFactory<TContext> is not covariant #30096

Open
@Driedas

Description

@Driedas

According to the official documentation of IDbContextFactory, the TContext parameter should be covariant:

TContext
The DbContext 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.

However, that is not the case in the source code

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<DbContextBase> contextFactory = _serviceProvider.GetRequiredService<IDbContextFactory<DbContextDerived>>();

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions