创建IDataProvider实例

using System;

namespace Demo.Data
{
public class DatabaseProvider
{
private static IDataProvider _instance = null;
private static object lockHelper = new object();

private DatabaseProvider()
{
}

static DatabaseProvider()
{
GetProvider();
}

//创建IDataProvider实例
private static void GetProvider()
{
try
{
var s = Type.GetType("Demo.Data.SqlServer.DataProvider,Demo.Data.SqlServer");
_instance = (IDataProvider)Activator.CreateInstance(Type.GetType(string.Format("Demo.Data.{0}.DataProvider, Demo.Data.{0}", "SqlServer"), false, true));
}
catch (Exception exp)
{
throw new Exception(exp.Message);
}
}

public static IDataProvider Instance()
{
if (_instance == null)
{
lock (lockHelper)
{
if (_instance == null)
{
GetProvider();
}
}
}
return _instance;
}

public static void ResetDbProvider()
{
_instance = null;
}
}
}

using System.Data;
using System.Data.SqlClient;

namespace Demo.Data.SqlServer
{
public partial class DataProvider : IDataProvider
{

//这个类必须实现IDataProvider接口

}
}


百度的解释,还是看不懂啊,还会出错有没有大佬帮我看看的。


生成dll为Music.Data.SqlServer.dll

如果还有其他数据库访问途径,类似方法
建其他的类库
配置文件中写上Access/SqlServer或者其他,
要和你的命名空间保持一致。因为反射时是根据命名空间+类名的方式创建对象的,如代码中的:
Type.GetType(string.Format("Music.Data.{0}.DataProvider,Music.Data.{0}", Configs.GetDbType)
里面的字符串就是你要创建的类的完整名字:
格式为:
Type.GetType("类完整名,程序集名");

类完整名=命名空间名+类名

下面的方法:
IDataProvider GetInstance()
就是使用单件模式,获取一个IDataProvider
里面使用了锁,防止多线程同时进行时冲突,这里面进行了判断,如果_instance为空就用上面的函数创建一个新的,然后返回。

最后一个方法是释放对象。

有时间去网上搜点反射方面的例子,单件模式应该很容易看懂的,就是用一个静态私有变量,只保持一个实例对象_instance存在。
建议研究一下PetShop源代码,然后关于三层和反射工厂就会有一个新的认识。
原文地址:https://www.cnblogs.com/miaololi/p/7243657.html