我尝试将connectionString传递给上下文工厂构造函数,但出现错误“找不到ContextImplementationTest的构造函数类型”是什么问题? 我在打电话
string bid="someCOnnectionString";
using (BaseContext<DbContext> db = MediaDbContext.GetBidContext(bid)){...}
public static class MediaDbContext
{
public static BaseContext<DbContext> GetBidContext(string connString)
{
//Settings.ContextFactory="ContextImplementationTest"
Type contextFactoryType = Type.GetType("Media.DB.Context.Implementation." + Settings.ContextFactory);
object[] args = new object[] { connString};
BaseContext<DbContext> instance = (BaseContext<DbContext>)Activator.CreateInstance(contextFactoryType, args);
return instance;
}
}
基本类
public class BaseContext<TContext> : DbContext where TContext : DbContext
{
static BaseContext()
{
Database.SetInitializer<TContext>(null);
}
protected BaseContext(string connectionString) : base(connectionString)
{
}...
儿童班
public class ContextImplementationTest : BaseContext<DbContext>
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{...}
更新:要在子类中调用构造函数,您需要在此类中具有构造函数。
儿童班
public class ContextImplementationTest : BaseContext<DbContext>
{
protected ContextImplementationTest(string connectionString) : base(connectionString)
{
}...
答案 0 :(得分:0)
Activator.CreateInstance仅在默认构造函数调用的情况下才使用nonPublic
参数。
您可以改用Type.GetConstructor:
Type contextFactoryType =
Type.GetType("Media.DB.Context.Implementation." + Settings.ContextFactory);
ConstructorInfo ci = contextFactoryType .GetConstructor(
BindingFlags.Instance | BindingFlags.NonPublic,
binder: null, new Type[] { typeof(string) }, modifiers: null);
object[] args = new object[] { connString };
var instance = (BaseContext<DbContext> instance)ci.Invoke(args);
return instance;