我已经在Startup.cs中注册了以下类。
services.AddScoped<ITestClass, TestClass>();
而且我在构造函数之一中询问此对象,并在操作方法中更新其值之一。
private ITestClass _testClass { get; set; }
#region Constructor
public MainController(ITestClass testClass)
{
_testClass = testClass;
}
public updateVlaue(int i)
{
_testClass .id = i;
...other code;
}
现在,我要在Singleton类中使用此对象值。类似于Microsoft扩展日志记录(创建的自定义记录器)。因为我不能在此singelton类中进行构造函数注入。我正在使用如下。
private IServiceProvider _serviceProvider { get; set; }
public CustomLogger(string categoryName, Func<string, LogLevel, bool> filter, IServiceProvider serviceProvider)
{
... other code
var serviceScope = serviceProvider.CreateScope();
_universalCallContext = serviceScope.ServiceProvider.GetRequiredService<IUniversalCallContext>();
}
现在它没有给我更新的对象(i值未更新)。
GetRequiredService()每次都会给我新对象吗?或如何保留已注册的同一对象?
您的问题尚不完全清楚,但是我怀疑如果更改此行,您会得到想要的结果:
services.AddScoped<ITestClass, TestClass>();
为此:
services.AddSingleton<ITestClass, TestClass>();
原始文件将为每个请求创建一个新实例;更正后的版本将为整个系统创建一个实例。