[Design Patterns]Repository Pattern

應用程式隨著雲端發展、分散式架構和資料庫的多樣性,資料來源不會只有一種,
為了整合這麼多種資料儲存類型,可以使用Repository Pattern 來切割DAL和BLL

好處

  • BLL不直接存取資料,關注點分離
  • 方便抽換DAL
  • 方便單元測試

先定義Model

1
2
3
4
5
6
7
8
9
10
11
namespace WebApp.Domain.Model
{
public class MemberInfo
{
public int MemberID { get; set; }

public string NickName { get; set; }

public string Email { get; set; }
}
}

建立介面

1
2
3
4
5
6
7
namespace WebApp.Domain.Repository
{
public interface IMemberInfoRepository
{
Tuple<Exception, MemberInfo> GetMemberInfo();
}
}

建立實體

  • MSSQL版本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
namespace WebApp.Persistent.SQL
{
public class MemberInfoRepository : IMemberInfoRepository
{
private string connectionString;

public MemberInfoRepository(string connectionString)
{
this.connectionString = connectionString;
}

public Tuple<Exception, MemberInfo> GetMemberInfo()
{
try
{
using (var conn = new SqlConnection(this.connectionString))
{
var result = conn.QueryFirstOrDefault<MemberInfo>(
"SPName",
param,
commandType: CommandType.StoredProcedure);

return Tuple.Create<Exception, MemberInfo>(null, result);
}
}
catch (Exception ex)
{
return Tuple.Create<Exception, MemberInfo>(ex, null);
}
}
}
}
  • Mongo版本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
namespace WebApp.Persistent.Mongo
{
public class MemberInfoRepository : IMemberInfoRepository
{
private const string collectionName = "MemberInfo";
private MongoClient client { get; set; }
private IMongoDatabase db { get; set; }
private IMongoCollection<MemberInfo> collection { get; set; }

static MemberInfoRepository()
{
BsonClassMap.RegisterClassMap<MemberInfo>(cm =>
{
cm.AutoMap();
cm.SetIgnoreExtraElements(true);
});
}

public MemberInfoRepository(string connectionString, string dbName)
{
client = new MongoClient(connectionString);
db = client.GetDatabase(dbName);
collection = db.GetCollection<MemberInfo>(collectionName);
}

public Tuple<Exception, MemberInfo> GetMemberInfo()
{
try
{
var result = this.collection.Aggregate().FirstOrDefault();
return Tuple.Create<Exception, MemberInfo>(null, result);
}
catch (Exception ex)
{
return Tuple.Create<Exception, MemberInfo>(ex, null);
}
}
}
}

請搭配Autofac服用

-------------The End-------------