Home > OS >  Pass a context as a parameter in .net core, c#
Pass a context as a parameter in .net core, c#

Time:01-12

I have the current situation, I have this base context from which I'm inheriting other two contexts

namespace AutoAttendant.Data
{
    public class BaseDbContext : DbContext
    {
        protected BaseDbContext(DbContextOptions<BaseDbContext> options)
            : base(options)
        {
        }

        protected BaseDbContext(DbContextOptions options)
            : base(options)
        {
        }

        public virtual DbSet<LockStatus> LockResult { get; set; }
    }

    public partial class AutoAttendantContext : BaseDbContext
    {
        internal AutoAttendantContext(DbContextOptions options)
            : base(options)
        {
        }

        public AutoAttendantContext(DbContextOptions<AutoAttendantContext> options)
            : base(options)
        {
        }
    }

    public partial class ReadOnlyAutoAttendantContext : BaseDbContext
    {
        internal ReadOnlyAutoAttendantContext(DbContextOptions options)
            : base(options)
        {
        }

        public ReadOnlyAutoAttendantContext(DbContextOptions<ReadOnlyAutoAttendantContext> options)
            : base(options)
        {
        }
    }
}

And I wanted to used this context as a parameter here

namespace AutoAttendant.API.ConfigurationExtensions
{
    public static class ServiceCollectionExtension
    {
        public static IServiceCollection AddPomeloDataSourceConfiguration(this IServiceCollection services, string connectionString, Version version, **BaseDbContext context**)
        {
            services.AddDbContextPool<**context**>(options => options.UseMySql(connectionString, new MySqlServerVersion(version), op =>
            {
                op.EnableRetryOnFailure();
            }));

            return services;
        }
    }
}

But I do not know how to pass it correctly because is used a type in the AddDbContextPool, any ideas?

CodePudding user response:

You can make your context type generic:

    public static IServiceCollection AddPomeloDataSourceConfiguration<TContext>(
        this IServiceCollection services, 
        string connectionString, 
        Version version, 
        TContext context)
        where TContext : BaseDbContext
    {
        services.AddDbContextPool<TContext>(options => options.UseMySql(connectionString, new MySqlServerVersion(version), op =>
        {
            op.EnableRetryOnFailure();
        }));

        return services;
    }

CodePudding user response:

You could pass it as a type parameter instead:

public static IServiceCollection AddPomeloDataSourceConfiguration<TContext>(this IServiceCollection services, string connectionString, Version version)
{
    services.AddDbContextPool<TContext>(options => options.UseMySql(connectionString, new MySqlServerVersion(version), op =>
    ...
}
  •  Tags:  
  • Related