在StackOverflow上,每个人都说-在使用ADO.NET或EF(调用方法Dispose或使用“ using”构造)时始终释放资源。 我在项目中使用了EF,ADO.NET和DI Unity(无UnityUnitWork模式),这使我很难弄清楚如何使用“使用”构造。而且我没有打电话给Dispose。 MSSQL连接没有问题。即使在连接字符串中添加“ Pooling = false”,连接也将在请求后立即关闭。 谁关闭我的联系?谁调用DataContext.Dispose()和DataContext.Connection.Close()?
示例:
public class Context
{
public static string TestConnectionString
{
get { return @"Data Source = (LocalDb)\MSSQLLocalDB; Initial Catalog = TestDb; Pooling = 'false';"; }
}
}
[Table(Name ="Requests")]
public class Request
{
[Column]
public int Id { get; set; }
[Column]
public int? OrderId { get; set; }
[Column]
public int StatusId { get; set; }
[Column]
public DateTime DateStart { get; set; }
[Column]
public DateTime DateEnd { get; set; }
[Column]
public bool IsActual { get; set; }
// ......
}
public class Repository: IDisposable
{
private DataDataContext db;
private Table<Request> table;
public Repository()
{
db = new DataContext(Context.TestConnectionString);
table = db.GetTable<Request>();
}
public void Dispose()
{
//db.Connection.Close();
//db.Dispose();
}
public IEnumerable<Request> GetAll(Expression<Func<Request, bool>> where)
{
return table.Where(where).ToList();
}
}
static void Main(string[] args)
{
Console.ReadLine();
Action action = () =>
{
for (int i = 0; i < 100; i++)
{
var repository = new Repository();
var requests = repository.GetAll(x => x.Id > 0);
//repository.Dispose();
Thread.Sleep(50);
}
};
Task.Run(action1);
Task.Run(action1);
Task.Run(action1);
Console.ReadLine();
}