Skip to content

Plugin problem while using multiple DbContext classes #654

Closed

Description

@faryu

Hi,
In a project I use the ef core library with the npgsql driver to access two different databases.
I'm using Npgsql.EFC.PostgreSQL version 2.1.2.

The first uses spatial data, so I use the .UseNetTopologySuite() Extension.
The second database doesn't use spatial data, so I ended up using the following:

services.AddDbContext<FirstContext>(
    options => options.UseNpgsql(connectionString1, opts => opts.UseNetTopologySuite());

services.AddDbContext<SecondDbContext>(
    options => options.UseNpgsql(connectionString2);

I received errors as soon as I added the second database in the code above. Specifically it seems to unload the NTS support added in the first context.

In order to solve this plugin issue I currently use the following:

services.AddDbContext<FirstContext>(
    options => options.UseNpgsql(connectionString1, opts => opts.UseNetTopologySuite());

services.AddDbContext<SecondDbContext>(
    options => options.UseNpgsql(connectionString2, opts => opts.UseNetTopologySuite());

I don't know if this is already known, so I'm reporting this issue just in case.

Activity

  1. austindrenski commented on Sep 28, 2018

    @austindrenski
    Contributor

    @faryu Thanks for reporting this. Would you please update your post with the exception and stack trace?

    INpgsqlOptions (e.g. opts in your snippet) is a singleton service, so it's likely that this is caused by the first configuration delegate being replaced (instead of wrapped by) the second configuration delegate.

    If that is indeed the case, we'll have to take another look and see if it's possible to scope the plugin registration by type of DbContext, as this has the potential to cause problems in multi-context apps.

    /cc @roji @YohDeadfall

    Related issue with the NodaTime plugin

    I'm appending this here since it seems to be related. I'll open a separate issue if it turns out to be unrelated.

    I recently found myself troubleshooting a similar issue with the NodaTime plugin. Based on an initial investigation of that issue, it seemed to be related to how we register types for plugins, specifically that we register them against NpgsqlConnection.GlobalTypeMapper.

    In that case, I was able to work around this by preemptively registering the driver plugin from the static constructor of my IStartup implementation:

    // N.B. the two `.UseNodaTime()` methods below are __not__ the same.
    
    static Startup()
    {
        // Registers the NodaTime plugin for the ADO.NET driver:  
        NpgsqlConnection.GlobalTypeMapper.UseNodaTime();
    
        ... // omitted
    }
    
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        ... // omitted
    
        // Registers the NodaTime plugin for the EF Core provider:
        services.AddDbContext<MyContext>(x => x.UseNpgsql(connectionString, y => y.UseNodaTime());
    
        ... // omitted
    }
  2. modified the milestones: 2.3.0, 3.0.0 on Oct 21, 2018
  3. austindrenski commented on Oct 21, 2018

    @austindrenski
    Contributor

    Assigning this to 3.0.0 as this may be impacted by upstream changes to the plugin model for 2.2.0.

    Plan to reevaluate after #672 is merged.

  4. removed their assignment
    on Nov 15, 2018
  5. austindrenski commented on Dec 15, 2018

    @austindrenski
    Contributor

    Reproduced in austindrenski/EFCore.PG-654 (v2.1.2).

    Unhandled Exception: System.InvalidOperationException: The property 'Point.Boundary' is of an interface type ('IGeometry'). If it is a navigation property manually configure the relationship for this property by casting it to a mapped entity type, otherwise ignore the property using the NotMappedAttribute or 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
       at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.PropertyMappingValidationConvention.Apply(InternalModelBuilder modelBuilder)
       at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnModelBuilt(InternalModelBuilder modelBuilder)
       at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
       at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
       at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
       at System.Lazy`1.CreateValue()
       at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()
       at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
       at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)
       at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope)
       at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)
       at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
       at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
       at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
       at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
       at Microsoft.EntityFrameworkCore.Internal.InternalAccessorExtensions.GetService[TService](IInfrastructure`1 accessor)
       at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.get_DatabaseCreator()
       at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.EnsureCreated()
       at EFCore.PG_654.Program.Main(String[] args) in C:\Users\adren\rider\EFCore.PG-654\Program.cs:line 31
    

    /cc @roji

  6. austindrenski commented on Dec 15, 2018

    @austindrenski
    Contributor

    I have not been able to reproduce this with EF Core v2.2.

    @faryu Could you upgrade your project to EF Core v2.2 and try this without the workaround you mentioned above?

  7. austindrenski commented on Dec 17, 2018

    @austindrenski
    Contributor

    I think I've got an explanation for what's happening here:

    1. IRelationalTypeMappingSource is registered as a singleton service.
    2. The Npgsql-specific plugin model used for EF Core 2.1 added type mappings loaded plugin-provided type mappings in the constructor of NpgsqlTypeMappingSource.

    This means that the Npgsql-specific plugin model (which was replaced for EF Core 2.2) only loads plugin-provided type mappings associated with the first DbContext to be resolved.

    If that first DbContext includes all of the plugins used by a second DbContext, then no exception would be thrown. But if a later DbContext needs some plugin that was not loaded by the first resolved DbContext, then an exception may be triggered in the normal course of type mapping.

    /cc @roji

  8. modified the milestones: 3.0.0, on Dec 17, 2018
  9. roji commented on Dec 31, 2018

    @roji
    Member

    @austindrenski based on #748 (comment) your analysis sounds right... Singleton services are indeed shared across context types (by default), and so the first context that was initialized determines which plugins are present.

    However, it seems that since we switched to the regular EF Core plugin model in 2.2 (good move...), we no longer have this problem. If that is indeed the case, then I think this issue should be closed - I don't think we should consider going back to 2.1 and trying to fix this with the older plugin model - let me know what you think.

  10. austindrenski commented on Dec 31, 2018

    @austindrenski
    Contributor

    However, it seems that since we switched to the regular EF Core plugin model in 2.2 (good move...), we no longer have this problem. If that is indeed the case, then I think this issue should be closed - I don't think we should consider going back to 2.1 and trying to fix this with the older plugin model - let me know what you think.

    I agree. I looked for possible mitigations that stopped short of a complete reimplementation, but it all looked worse than the status quo.

  11. removed this from the milestone on Dec 31, 2018
  12. added theissue type on Jun 19, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions