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);
}
View Code
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);
}
View Code

注入时:

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);
});
View Code

 使用时:构造函数注入

public XXService(Func<string, DbContext> DbContexts)
{
  _x1Context = DbContexts("X1Context") as x1_Context;
  _x2Context = DbContexts("X2Context") as x2_Context;
}
View Code

 方法二:

不注入 Func<string, DbContext>

直接构造函数使用 Autofac.Features.Indexed.IIndex<string, DbContext> DbContexts 读取

 

posted @ 2020-12-23 16:41  狂想NICE  阅读(1146)  评论(0编辑  收藏  举报