1 回答
TA贡献1829条经验 获得超4个赞
这个问题是缺少注册的,DbContextOption它是初始化目标数据库上下文所需的构造函数的一部分。
在内部就是这样RegisterPluginDataContext做的。
/// <summary>
/// Represents extensions of Autofac ContainerBuilder
/// </summary>
public static class ContainerBuilderExtensions
{
/// <summary>
/// Register data context for a plugin
/// </summary>
/// <typeparam name="TContext">DB Context type</typeparam>
/// <param name="builder">Builder</param>
/// <param name="contextName">Context name</param>
public static void RegisterPluginDataContext<TContext>(this ContainerBuilder builder, string contextName) where TContext : DbContext, IDbContext
{
//register named context
builder.Register(context => (IDbContext)Activator.CreateInstance(typeof(TContext), new[] { context.Resolve<DbContextOptions<TContext>>() }))
.Named<IDbContext>(contextName).InstancePerLifetimeScope();
}
}
DbContextOptions<TContext>请注意,它在激活上下文时尝试解析。
您需要构建数据库上下文选项并将其提供给容器,以便在解析时可以将其注入到上下文中。
private const string CONTEXT_NAME ="nop_object_context_bookappointment";
public void Register(ContainerBuilder builder, ITypeFinder typeFinder, NopConfig config) {
//...code removed for brevity
var optionsBuilder = new DbContextOptionsBuilder<BookAppointmentDBContext>();
optionsBuilder.UseSqlServer(connectionStringHere);
DbContextOptions<BookAppointmentDBContext> options = optionsBuilder.Options;
builder.RegisterInstance<DbContextOptions<BookAppointmentDBContext>>(options);
//data context
builder.RegisterPluginDataContext<BookAppointmentDBContext>(CONTEXT_NAME);
//...code removed for brevity
}
- 1 回答
- 0 关注
- 99 浏览
添加回答
举报