代码之家  ›  专栏  ›  技术社区  ›  si2030

C#Dotnet核心-在构造函数中实现泛型DBContext的问题

  •  0
  • si2030  · 技术社区  · 5 年前

    我正努力从长期失业中恢复过来。

    question 关于在我的通用基本存储库中配置DBContext。只有在用户登录之后,我才能构造一个连接字符串,这样我就不能在中注册服务启动.cs-我必须使用构造函数参数来实例化DBContext。

    我知道了 answer

    public class ContextFactory<T> : IContextFactory<T> : where T : DbContext
    {
        public T CreateDbContext(string connectionString)
        {
            var optionsBuilder = new DbContextOptionsBuilder<T>();
            optionsBuilder.UseSqlServer(connectionString);
            return new T(optionsBuilder.Options);
        }
    }
    

    错误在返回线上 new T(optionsBuilder.Options);

    使用new()约束

    0 回复  |  直到 5 年前
        1
  •  5
  •   Shahzad Hassan    5 年前

    即使你加上 new() 约束时,将出现以下错误

    “T”:创建变量类型的实例时不能提供参数。

    给你的代码无效。

    参考 new constraint (C# Reference)

    Activator.CreateInstance (Type, Object[])

    鉴于

    public interface IContextFactory<TContext> where TContext : DbContext {
        TContext Create(string connectionString);
    }
    

    您将按以下方式实现它

    public class ContextFactory<TContext> : IContextFactory<TContext>
        where TContext : DbContext {
    
        public TContext Create(string connectionString) {
            var optionsBuilder = new DbContextOptionsBuilder<TContext>();
            optionsBuilder.UseSqlServer(connectionString);
            return (TContext)Activator.CreateInstance(typeof(TContext), optionsBuilder.Options);
        }
    }
    

    public class ContextFactory<TContext> : IContextFactory<TContext>
        where TContext : DbContext {
    
        public TContext Create(DbContextOptions<TContext> options) {
            return (TContext)Activator.CreateInstance(typeof(TContext), options);
        }
    }
    

    因此,建设者将成为工厂所在地的责任人。

    var connection = @"....";
    var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
    optionsBuilder.UseSqlServer(connection);
    
    //Assuming factory is `IContextFactory<BloggingContext>`    
    using (var context = factory.Create(optionsBuilder.Options))
    {
       // do stuff
    }
    

    工厂可以在中注册为开放泛型 ConfigureServices 方法

    services.AddSingleton(typeof(IContextFactory<>), typeof(ContextFactory<>));