gpt4 book ai didi

c# - 使用 IRepository 和彼此的 ASP.NET C# 服务

转载 作者:太空宇宙 更新时间:2023-11-03 10:42:02 24 4
gpt4 key购买 nike

我有我的 IRepository 接口(interface),它使用 NinjectInRequestScope 绑定(bind)。

存储库绑定(bind)是:

kernel.Bind<IRepository>().To<DefaultRepository>().InRequestScope().WithConstructorArgument("dbContext", dbContext => kernel.Get<DefaultContext>());

如果我有一个以相同方式绑定(bind)的服务 IAccountService

具体实现:

public class AccountService : IAccountService
{
IRepository _repository;

public AccountService(IRepository repository) { _repository = repository; }
}

如果我现在创建另一个以相同方式绑定(bind)的服务 IBlogService

具体实现:

public class BlogService : IBlogService
{
IRepository _repository;
IAccountService _accountService;

public AccountService(IRepository repository, IAccountService accountService)
{
_repository = repository;
_accountService = accountService;
}
}

这两个服务都在请求 IRepository,它们是在获取相同的实例还是在请求两个完全不同的隔离 DbContext

它确实“有效”,但这种方法有明显的缺点吗?

最佳答案

因为您使用 .InRequestScope(),所以在您的请求期间,所有服务都将获得相同的 DefaultRepository 实例。因此,当收到新请求时,将创建 DefaultRepository 的新实例。

此外,如果您的 IRepository 接口(interface)实现了 IDisposable,Ninject 将在需要时处理它。

我不认为有任何失败,因为在 Web 应用程序中,您的 DbContext 的生命周期应该是每个请求(除非您有充分的理由不遵循这种方法)。

编辑

您还可以实现每个请求模式的事务,这样您就可以避免在一个存储库中保存成功但在另一个存储库中保存失败的不一致。这样,如果在请求期间出现任何问题,您可以回滚所有更改。

并不是说您应该实现它,只是想让您知道这是可能的。这是一个非常基本的例子,你应该在你想创建一个事务时做一些额外的检查(例如只在 http POSTS 上),也许你想把它委托(delegate)给一个单独的类这样你的 Global.asax 就不会困惑有了所有这些责任。另一件需要提及的事情是,这仅在您的 DbContext 中注入(inject)了 .InRequestScope() 时才有效,因此在您的请求中使用相同的上下文。

它是这样工作的:

在您的 Global.asax Application_BeginRequest() 方法中,您应该像这样初始化您的事务:

  var transaction = _context.Database.BeginTransaction(IsolationLevel.ReadCommitted);
_httpContext.Items["_Transaction"] = transaction;

在您的 Global.asax Application_Error() 方法中,您可以像这样设置一个错误标志

_httpContext.Items["_Error"] = true;

最后,在您的 Global.asax Application_EndRequest() 中,如果没有错误,您可以提交所有内容,否则回滚:

  var transaction = (DbContextTransaction)_httpContext.Items["_Transaction"];

if (_httpContext.Items["_Error"] != null)
transaction.Rollback();
else
transaction.Commit();

关于c# - 使用 IRepository 和彼此的 ASP.NET C# 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24992369/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com