用抽象工厂来解决多数据库之间的切换问题是普遍的,像以下几篇文章都讲的很具体
申明之前写的存在强大漏洞 -- 之前有涉及到IoC Autofac的知识点,鄙人孤陋寡闻,在亲身实践后才发现其中奥妙可参照一下几篇文章
http://www.codePRoject.com/Articles/808894/IoC-in-asp.net-MVC-using-Autofac
http://code.google.com/p/autofac/wiki/Mvc3Integration
http://www.VEVb.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://www.VEVb.com/tiger8000/archive/2012/01/04/2312134.html
但是考虑到在服务器上资源释放的问题,还是会选择采用另一种实现方式
先新建一个类库 Interface,这个类库对谁都不依赖,这里有各种抽象的方法,但并没有关于数据库连接啊或者操作之类的抽象方法,这里定义的抽象方法和controller里的对应,
1: namespace WebApi.Interface
2: {
3: public interface ICommon
4: {
5: int regist(String LoginName, String PassWord);
6: }
7: }
再定义一个具体的实现的类库
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里实现一个或多个接口就可以了
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: }
针对不同的数据库写不同的实现的类库,就能做到多数据库的切换了,还的记得子啊webconfig中申明是对哪个实现的实现
<add key="LoadAssembly" value="WebApi.OracleImp"/>,这样切换不同的实现时就可以实现对里面不同实现方法的实现。
这里要实现各依赖项的加载还必须要做到一下几步:
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);
至于为什么需要好好研究会
新闻热点
疑难解答