读 WriteSqlServiceContext : SqlServiceContext { public WriteSqlServiceContext() : base("") { } } 写 ReadSqlServiceContext : SqlServiceContext { public ReadSqlServiceContext() : base("") { } }
View Code通过工厂类进行初始化
上下文工厂类 Contextfactory { 获取上下文 DbContext GetContext(DbOpertionType OpertionType) { DbContextType ContextType = DBInitializer.DbContextType; if (ContextType == DbContextType.MySql) { if (OpertionType == DbOpertionType.Read) return new ReadMySqlContext(); WriteMySqlContext(); } else { if (OpertionType == DbOpertionType.Read) return new ReadSqlServiceContext(); WriteSqlServiceContext(); } } 获取上下文操作 TEntity CallContext<TEntity>(DbOpertionType OpertionType) where TEntity: DbContext { var DbContext = GetContext(OpertionType); return (TEntity)DbContext; } }
View Code最后配置webcofig即可
<!--数据库配置(WriteMySqlConnection:读数据库,ReadMySqlConnection:写数据库 如果无需要进行 就配置IsUsedWR,2个链接都写写入库)--> <connectionStrings> <add name=connectionString=providerName=/> <add name=connectionString=providerName=/> </connectionStrings> <!--数据库读取分离配置--> <!--是否开启读写分离 1:开启 0:不开启--> <add key=value=/>
View Code最后进行测试
public class TestController : Controller { private ITestService _TestServiceDb { get; set; } public TestController(ITestService TestServiceDb) { _TestServiceDb = TestServiceDb; } ActionResult Index() { }); var NewResult = _TestServiceDb.GetEntityByID(result.ID); return View(); } }
View Code搞定,可能在代码上有点累赘,但是总算是可行的。
如果有兴趣的朋友可以留下邮箱,然后发全代码一起研究,谢谢!