Autofac注入多数据库(DbContext)
初始化DbContext
public partial class x1_Context : DbContext { public hw_siteContext() { } public hw_siteContext(DbContextOptions<hw_siteContext> options) : base(options) { } ... protected override void OnModelCreating(ModelBuilder modelBuilder) { ... } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder.UseMySql("..."); } } partial void OnModelCreatingPartial(ModelBuilder modelBuilder); }
public partial class x2_Context : DbContext { public hw_siteContext() { } public hw_siteContext(DbContextOptions<hw_siteContext> options) : base(options) { } ... protected override void OnModelCreating(ModelBuilder modelBuilder) { ... } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder.UseMySql("..."); } } partial void OnModelCreatingPartial(ModelBuilder modelBuilder); }
注入时:
builder.RegisterType<x1_Context>().AsImplementedInterfaces().Named<DbContext>("X1Context"); //指定DbContext别名,方便注入 builder.RegisterType<x2_Context>().AsImplementedInterfaces().Named<DbContext>("X2Context"); //指定DbContext别名,方便注入 builder.Register<Func<string, DbContext>>(c=> { var cc = c.Resolve<IComponentContext>(); return named => cc.ResolveNamed<DbContext>(named); });
使用时:构造函数注入
public XXService(Func<string, DbContext> DbContexts) { _x1Context = DbContexts("X1Context") as x1_Context; _x2Context = DbContexts("X2Context") as x2_Context; }
方法二:
不注入 Func<string, DbContext>
直接构造函数使用 Autofac.Features.Indexed.IIndex<string, DbContext> DbContexts 读取