我一直在缓慢而确定地解决因应用程序使用率上升而导致超时显示的问题。我一直在使用DI的仓库式架构。
开发应用程序时,选择单例模式来服务数据控制器,因为每个会话只会触发一个,并在需要时才实例化。
但是,用户使用率增加了,我遇到了线程问题。
我有75个左右的数据控制器,它们都是按照以下模式开发的。
public class MyService : IMyServiceBase
{
internal MyServiceDataDataContext _dataContext = null;
protected IConfigurationService _systemService;
public MyService(IConfigurationService systemService)
{
_systemService = systemService;
_dataContext = new MyServiceDataDataContext(_systemService.GetCurrentSystem().WriteOnlyDatabase.ConnectionString);
_dataContext.ObjectTrackingEnabled = false;
}
public Domain.Data.MyObject GetSomething(int id)
{
return (
from s in _dataContext.MyObjects
select Mapper.Map<MyObject, Domain.Data.MyObject>(s)
).SingleOrDefault();
}
}
现在,经过一些研究,我发现我在使用最频繁的控制器时遇到了轻微的并发问题。我一直在对最常用的应用程序进行以下修复,发现可以解决生产服务器上的问题。简而言之,我将在每个函数调用中针对每个请求创建数据上下文,这是预期的单例方式。
public class MyService : IMyServiceService
{
internal MyServiceDataDataContext _dataContext = null;
protected IConfigurationService _systemService;
public MyService(IConfigurationService systemService)
{
_systemService = systemService;
_dataContext = new DistrictDataDataContext(_systemService.GetCurrentSystem().WriteOnlyDatabase.ConnectionString);
_dataContext.ObjectTrackingEnabled = false;
}
public Domain.Data.MyObject GetSomething(int id)
{
using (_dataContext = new MyServiceDataDataContext(_systemService.GetCurrentSystem().WriteOnlyDatabase.ConnectionString))
{
Mapper.CreateMap<MyObject, Domain.Data.MyObject>();
return (from s in _dataContext.MyObjects
select Mapper.Map<MyObject, Domain.Data.MyObject>(s)).SingleOrDefault();
}
}
}
现在的问题...最好是使用所有75个数据控制器并重构所有方法,按照上面的示例,某些控制器有20个方法,或者我可以简单地停止在DI构造函数中使用单例。
将以下代码片段更改为每次调用都与在每个方法中调用构造函数相同吗?
AppServiceFactory.Instance.RegisterTypeSingleton<IMyService>(typeof(My.Resources.Data.MyService), "MyService");
谢谢
最佳答案
您应该对所有控制器进行一次更改-注入DataContext
。
public class MyService : IMyServiceBase
{
private MyServiceDataDataContext dataContext;
public MyService(MyServiceDataDataContext dataContext)
{
this.dataContext = dataContext;
}
public Domain.Data.MyObject GetSomething(int id)
{
return (
from s in this.dataContext.MyObjects
select Mapper.Map<MyObject, Domain.Data.MyObject>(s))
.SingleOrDefault();
}
}
每个对象的生存期(在您的示例中为
DataContext
)的责任应该在使用者(MyService
)的外部-容器可以并且应该管理所有对象的生存期。关于c# - 更改DI容器的实例化类型以进行100多种更改,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26965306/