用抽象工廠來解決多數(shù)據(jù)庫之間的切換問題是普遍的,像以下幾篇文章都講的很具體
申明之前寫的存在強(qiáng)大漏洞 -- 之前有涉及到IoC Autofac的知識(shí)點(diǎn),鄙人孤陋寡聞,在親身實(shí)踐后才發(fā)現(xiàn)其中奧妙可參照一下幾篇文章
http://www.codePRoject.com/Articles/808894/IoC-in-asp.net-MVC-using-Autofac
http://code.google.com/p/autofac/wiki/Mvc3Integration
http://m.survivalescaperooms.com/zhouruifu/archive/2012/04/03/dependency-injection-in-asp-net-web-api-using-autofac.html
http://blog.csdn.net/zouyujie1127/article/details/15341569
http://m.survivalescaperooms.com/tiger8000/archive/2012/01/04/2312134.html
但是考慮到在服務(wù)器上資源釋放的問題,還是會(huì)選擇采用另一種實(shí)現(xiàn)方式
先新建一個(gè)類庫 Interface,這個(gè)類庫對(duì)誰都不依賴,這里有各種抽象的方法,但并沒有關(guān)于數(shù)據(jù)庫連接啊或者操作之類的抽象方法,這里定義的抽象方法和controller里的對(duì)應(yīng),
1: namespace WebApi.Interface
2: {3: public interface ICommon
4: {5: int regist(String LoginName, String PassWord);
6: } 7: }再定義一個(gè)具體的實(shí)現(xiàn)的類庫
1: namespace WebApi.OracleImp
2: {3: public class Common: WebApi.Interface.ICommon
4: {5: public int regist(String LoginName, String Password)
6: {7: using (var conn = new System.Data.OracleClient.OracleConnection(OracleHelper.ConnString))
8: { 9: conn.Open();10: using (var command = conn.CreateCommand())
11: { 12: command.Parameters.Clear();13: command.Parameters.Add(new System.Data.OracleClient.OracleParameter(":LoginName", LoginName));
14: command.Parameters.Add(new System.Data.OracleClient.OracleParameter(":Password", Password));
15: command.CommandText = "insert into YG(DLM,MM) value(:LoginName,:Password)";
16: var result = command.ExecuteNonQuery;17: return result;
18: } 19: } 20: } 21: } 22: }最后在Controller里實(shí)現(xiàn)一個(gè)或多個(gè)接口就可以了
1: Interface.ICommon _common;2: public DemoController(Interface.ICommon common)
3: {4: this._common = common;
5: } 6: [HttpPost]7: public int regist(String LoginName, String Password)
8: { 9: 10: if (String.IsNullOrWhiteSpace(Password))
11: {12: throw new exception("password為空");
13: }14: if (String.IsNullOrWhiteSpace(LoginName))
15: {16: throw new exception("(LoginName))為空");
17: } 18: 19: var result = _common.regist(LoginName, Password);20: return result;
21: }針對(duì)不同的數(shù)據(jù)庫寫不同的實(shí)現(xiàn)的類庫,就能做到多數(shù)據(jù)庫的切換了,還的記得子啊webconfig中申明是對(duì)哪個(gè)實(shí)現(xiàn)的實(shí)現(xiàn)
<add key="LoadAssembly" value="WebApi.OracleImp"/>,這樣切換不同的實(shí)現(xiàn)時(shí)就可以實(shí)現(xiàn)對(duì)里面不同實(shí)現(xiàn)方法的實(shí)現(xiàn)。
這里要實(shí)現(xiàn)各依賴項(xiàng)的加載還必須要做到一下幾步:
1.先添加引用
using Autofac;
using Autofac.Integration.WebApi;
2.
var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(Assembly.Load(ConfigurationSettings.AppSettings["LoadAssembly"]))
.Where(t => true)
.AsImplementedInterfaces();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
var container = builder.Build();
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
至于為什么需要好好研究會(huì)
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注