即使你加上
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<>));