处理统一数据库上下文的正确方式



我正在使用统一和依赖注入,目前,我对连接的处理有点困惑。

我将举一个例子,希望我能正确解释:)

我有一个使用服务的控制器:

public class CompaniesController : IDatabaseController
{
private readonly ICompaniesService _companiesService;
public CompaniesController(ICompaniesService companiesService)
{
_companiesService = companiesService;
}
}

并且该服务被注册到UnityConfig为:

container.RegisterType<ICompaniesService, CompaniesService>(new HierarchicalLifetimeManager());

***我读到,如果我使用IDisposable,那么HierarchicalLifetimeManager是强制性的。

实现接口的服务(我知道数据库连接也可以注入,但由于超出问题范围的原因,请忽略它)如下:

public class CompaniesService : ICompaniesService
{
private readonly DatabaseContext _db = Helpers.GetDatabaseContextForRequest();
/// <summary>
/// Returns all employee of a company
/// </summary>
/// <param name="company_id">The id of the company</param>
/// <returns>A collection of EmployeeDAP</returns>
public IEnumerable<EmployeeDAP> GetCompanyEmployees(int company_id)
{
var employees = CompaniesRepository.GetCompanyEmployees(company_id);
return employees;
}
}

问题来了。我应该实现服务的IDisposable接口并处理数据库连接吗?还是GC来清理混乱?

如果我必须手动处理连接,我应该使用处理模式或吗

public void Dispose()
{
((IDisposable)_db).Dispose();
}

是否足够?

提前感谢

更新:

辅助方法如下:

try
{
DatabaseContext db = (DatabaseContext)getRequestValue(name);
if (db == null || !db.Database.Exists())
{
db = new DatabaseContext();
setDatabaseContextForRequest(db, name);
}
return db;
}
catch (Exception)
{
return new DatabaseContext();
}

其中新的DatabaseContext继承自EF的DbContext。

我认为让服务来处理DatabaseContext给了服务太多的责任。

我会将DatabaseContext配置从Helpers类移动到Unity,并使用PerRequestLifetimeManager进行注册
使用Unity作为生存期管理器,您将获得一个跨HTTP请求的DatabaseContext,使HTTP请求的生存期近似于DatabaseContext的生存期。

这种方法可以避免让服务拥有DatabaseContext生存期的所有权,将所有清理逻辑和所有权保留在Unity容器中。此外,您将能够在单个请求中的服务之间安全地共享DatabaseContext实例,因为DatabaseContext仅在请求结束时被释放。

最后,记住,一旦你处理了一些东西,你就不能再使用它了,所以你必须改进Helpers.GetDatabaseContextForRequest(),以便在它被处理时重新创建DatabaseContext

最新更新