C# 建立数据库连接的最佳方法是什么(静态、抽象、每个请求等)?
我使用了很多连接到db的模型,在我上一个与C#&entity framework合作的项目中,我为db连接创建了静态类,但我在打开和关闭连接时遇到了问题,因为当超过10-15个请求聚集在一起时,会出现错误,我通过改变连接db的方法解决了这个问题,我现在根据请求连接,并删除了所有静态方法和类 现在我想知道 建立连接的最佳模式是什么?C# 建立数据库连接的最佳方法是什么(静态、抽象、每个请求等)?,c#,entity-framework,design-patterns,C#,Entity Framework,Design Patterns,我使用了很多连接到db的模型,在我上一个与C#&entity framework合作的项目中,我为db连接创建了静态类,但我在打开和关闭连接时遇到了问题,因为当超过10-15个请求聚集在一起时,会出现错误,我通过改变连接db的方法解决了这个问题,我现在根据请求连接,并删除了所有静态方法和类 现在我想知道 建立连接的最佳模式是什么? 我应该在每次查询后关闭它并在使用之前打开它还是 静态类中的连接是一个很好的模型(我不需要这样做) 每次都要创造它吗 这个问题有好的设计模式吗 所有这些都是为了同一个问
现在,连接到DB的最佳模式是什么?通过人工请求、线程请求或每个事务..我认为每个请求的伸缩性最好。使用线程安全连接池,并使连接范围与工作单元一致。让负责事务行为和工作单元的服务签出连接,使用它,并在提交或回滚工作单元时将其返回到池中 更新: 10-12秒提交状态更新?你做错了别的事。你的书面问题不足以提供合适的答案 是1.3B个事务,每天8小时的计算结果是每秒约45K个事务。你们的交易量是纳斯达克的两倍。如果你想用一台机器,我会说纳斯达克使用的服务器不止一台
我还想知道你是否可以不使用ACID更新状态。毕竟。也许更好的解决方案是使用生产者/消费者模式和阻塞队列,在发送状态后尽可能更新这些状态。问题的答案:
以下是我对架构的建议:
还有一件事,我不建议为此使用实体框架,因为它有太多的工作要做。这种任务只需调用3-4个存储过程即可。请看一看——它是一个非常轻量级的MicroDal框架,在大多数情况下比EF(实体框架)快10倍以上。我应该在每次查询后关闭它吗? .Net会为您这样做,所以让它来处理它,这是一个垃圾收集器任务。所以不要费心手动处理对象,这是Jon Skeet的一个很好的答案:。但是,您可以使用
using(IDisposable){}
语句强制GC执行其工作。下面是一篇关于资源重新分配的好文章:
2。静态类中的连接是否良好?
从不创建数据上下文
public class FooContextService {
private readonly FooContext _ctx;
public FooContext Context { get { return _ctx; } }
public FooContextService() {
_ctx = new FooContext();
}
}
public class UnicornService {
private readonly FooContext _ctx;
public UnicornService(FooContextService contextService) {
if (contextService == null)
throw new ArgumentNullException("contextService");
_ctx = contextService.Context;
}
public ICollection<Unicorn> GetList() {
return _ctx.Unicorns.ToList();
}
}
public class DragonService {
private readonly FooContext _ctx;
public DragonService(FooContextService contextService) {
if (contextService == null)
throw new ArgumentNullException("contextService");
_ctx = contextService.Context;
}
public ICollection<Dragon> GetList() {
return _ctx.Dragons.ToList();
}
}
public class FantasyController : Controller {
private readonly FooContextService _contextService = new FooContextService();
private readonly UnicornService _unicornService;
private readonly DragonService _dragonService;
public FantasyController() {
_unicornService = new UnicornService(_contextService);
_dragonService = new DragonService(_contextService);
}
// Controller actions
}
public class FooContextService {
private readonly FooContext _ctx;
public FooContext Context { get { return _ctx; } }
public FooContextService() : this(true) { }
public FooContextService(bool proxyCreationEnabled) {
_ctx = new FooContext();
_ctx.Configuration.ProxyCreationEnabled = proxyCreationEnabled;
}
}
(_context as IObjectContextAdapter).ObjectContext.Connection.Open();