编辑:由于许多用户错误地将此视为ASP.NET特定问题。请注意,我的应用程序不是Web应用程序,我没有使用ASP.NET应用程序(我正在使用其功能,该功能在.NET Core中也可用)。
最近,当我在配置一个Entity Framework DbContext的生命周期时,在Ninject DI中,我一直在研究.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具有InRequestScope方法,但仅适用于Web应用程序,因此与.NET Core DI ServiceLifetime.Scoped
设置非常不同。
也许我需要在Ninject中创建某种自定义范围,但是-我无法确切说明如何实现与.NET Core DI中相同的作用域行为。为此,我需要了解.NET Core应用程序在.NET Core DI上下文中的作用域生命周期是如何工作的。 我猜测,创建了一个DbContext实例,并在应用程序退出时被处理。
因此我的问题是:
- .NET Core DI的
scope
生命周期设置是如何工作的,它的生命周期是什么? - Ninject DI是否可以实现类似的行为?
InRequestScope
移植到.NET Core应用程序中,就像.NET Core DI正在做的那样。我已经编辑了问题,现在更清楚了 :) - Categle