【发布时间】:2015-06-03 15:32:32
【问题描述】:
我有一个网络应用程序,你已经知道这个应用程序会有很多请求,每个请求都将在不同的线程上运行,这意味着如果我使用单例访问我的 DAL 库,这不会有问题。
但是我不确定这是否是最好的方法,因为我读到一个请求有时我使用不同的线程,而且我还读到锁定线程有时会导致使用单个实例时性能下降。
为了让你更了解我,这就是我打算做的:
DAL
这是一个好方法吗?
这是我打算使用的单例:
public static Products Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Products instance = new Products();
注意:我的 Dal 将使用 ADO.NET 访问数据库(我有理由使用 ado),而 BAL 只会使用此方法进行选择或 CRUD 操作。
我的 Ado.NET 代码:
public static readonly string ConnectionString = @"Server=localhost;Database=test;Uid=root;Pwd=test;";
public bool IsProduct(string name)
{
var conn = new SqlConnection(ConnectionString);
bool result;
try
{
conn.Open();
var command = new SqlCommand();
SqlParameter[] parameters = new SqlParameter[1];
parameters[0] = new SqlParameter("@Product", name);
command.Connection = conn;
command.CommandText = "SPC_GET_PRODUCT";
command.CommandType = System.Data.CommandType.StoredProcedure;
result = Convert.ToBoolean(command.ExecuteScalar());
}
finally
{
conn.Close();
conn.Dispose();
}
return result;
}
谢谢。
【问题讨论】:
-
我们不知道。我们看不到您的 DAL 是如何实现的。是实体框架吗?它在自己的服务中吗?您的单身人士如何“访问” DAL?
-
我更新了问题。
-
这没有多大帮助,也没有回答我提出的任何问题。
-
是实体框架吗?不,它是 ADO.NET。您的单身人士如何“访问”DAL? Products.Instance.GetProducts();
-
“GetProducts()”是做什么的?我们必须看看它是否是线程安全的代码。
标签: c# asp.net-mvc design-patterns singleton 3-tier