最近,在 Ninject DI 中配置 Entity Framework DbContext 生存期时,我一直在挖掘 .NET Core 依赖注入,因为它已经具有注册 DbContext 的功能,可以在这里找到。默认上下文生命周期为ServiceLifetime.Scoped.
在代码一览中,我们可以看到在 ASP.NET 应用程序中,“scoped”意味着:
范围是围绕每个服务器请求创建的
namespace Microsoft.Extensions.DependencyInjection
{
//
// Summary:
// Specifies the lifetime of a service in an Microsoft.Extensions.DependencyInjection.IServiceCollection.
public enum ServiceLifetime
{
//
// Summary:
// Specifies that a single instance of the service will be created.
Singleton = 0,
//
// Summary:
// Specifies that a new instance of the service will be created for each scope.
//
// Remarks:
// In ASP.NET Core applications a scope is created around each server request.
Scoped = 1,
//
// Summary:
// Specifies that a new instance of the service will be created every time it is
// requested.
Transient = 2
}
}
我正在尝试在 Ninject DI 中实现类似的功能,但在谈到 .NET Core 应用程序(这不是 Web 应用程序!)时,很难说明 Ninject 中的作用域生命周期相当于什么。
Ninject 有InRequestScope方法,但它仅适用于 Web 应用程序,因此它与 .NET Core DIServiceLifetime.Scoped设置确实不同。
也许我必须在 Ninject 中创建某种自定义范围,但是 - 我仍然无法说明如何实现与 .NET Core DI 中完全相同的范围行为。为此,我需要了解范围生命周期在 .NET Core DI 中的 .NET Core 应用程序上下文中是如何工作的。我的猜测是,有一个 DbContext 实例正在被创建,一旦应用程序退出就会被释放。
因此我的问题:
.NET Core DIscope生命周期设置是如何工作的?它的生命周期是什么?
是否有可能在 Ninject DI 中实现类似的行为?
慕娘9325324