尽管有依赖注入,但属性为 null
Attributes null despite Dependency Injection
我想使用 Depedency Injection 在多个控制器中使用一个对象。
但是对象的变量总是null。
我想在多个 class 中使用其属性的 class:
public class Info
{
public string DriveId {get; set;}
public string ItemId {get; set;}
public int SubscriptionTime {get; set;}
public string PdfItemId {get; set;}
}
控制器 class 1:
//...
private Info info;
public SubscriptionController(Info info)
{
this.Info = info;
}
[HttpGet]
public async Task<ActionResult<string>> Get(string driveId, string itemId, string pdfItemId, int subscriptionTime)
{
//......
Info = new Info{DriveId = driveId, ItemId = itemId,
SubscriptionTime = subscriptionTime, PdfItemId = pdfItemId}; //Here the class (Info) is instantiated:
//......
}
startup.cs中的配置:
public void ConfigureServices(IServiceCollection services)
{
//....
services.AddScoped<IFileService, FileService>(); //Database service class: it runs without problems
services.AddScoped<Info>(); //But this scope somehow causes me problems.
//...
}
在另一个控制器中,我需要实例(来自 Info),根据调试器和控制台,它为空。
控制器 class 2:
//...
private Info info;
public OtherController(Info info)
{
this.Info = info;
}
[HttpGet]
public IActionResult GetActionResult()
{
Console.WriteLine(info.DriveId);
//...
}
我犯了哪些初学者的错误?
AddScoped
,就像您所做的那样,使用范围内的生命周期(单个请求的生命周期)注册服务。下次您发出请求时,另一个 Info 实例将被注入到 Controller(s) 中。
AddSingleton
将为整个应用程序注册一个单例(只有一个实例)。但是,只要应用程序存在,您的 Info
实例就会在所有请求之间共享。因此,应用程序的每个用户在每次发出请求时都会共享相同的 Info
实例。
但是,尽管我不知道您的应用程序的性质,但您在这里尝试实现的目标非常奇怪:为通过控制器输入的依赖注入注入的东西设置值并不是事情的方式通常都完成了。
我想使用 Depedency Injection 在多个控制器中使用一个对象。 但是对象的变量总是null。
我想在多个 class 中使用其属性的 class:
public class Info
{
public string DriveId {get; set;}
public string ItemId {get; set;}
public int SubscriptionTime {get; set;}
public string PdfItemId {get; set;}
}
控制器 class 1:
//...
private Info info;
public SubscriptionController(Info info)
{
this.Info = info;
}
[HttpGet]
public async Task<ActionResult<string>> Get(string driveId, string itemId, string pdfItemId, int subscriptionTime)
{
//......
Info = new Info{DriveId = driveId, ItemId = itemId,
SubscriptionTime = subscriptionTime, PdfItemId = pdfItemId}; //Here the class (Info) is instantiated:
//......
}
startup.cs中的配置:
public void ConfigureServices(IServiceCollection services)
{
//....
services.AddScoped<IFileService, FileService>(); //Database service class: it runs without problems
services.AddScoped<Info>(); //But this scope somehow causes me problems.
//...
}
在另一个控制器中,我需要实例(来自 Info),根据调试器和控制台,它为空。 控制器 class 2:
//...
private Info info;
public OtherController(Info info)
{
this.Info = info;
}
[HttpGet]
public IActionResult GetActionResult()
{
Console.WriteLine(info.DriveId);
//...
}
我犯了哪些初学者的错误?
AddScoped
,就像您所做的那样,使用范围内的生命周期(单个请求的生命周期)注册服务。下次您发出请求时,另一个 Info 实例将被注入到 Controller(s) 中。
AddSingleton
将为整个应用程序注册一个单例(只有一个实例)。但是,只要应用程序存在,您的 Info
实例就会在所有请求之间共享。因此,应用程序的每个用户在每次发出请求时都会共享相同的 Info
实例。
但是,尽管我不知道您的应用程序的性质,但您在这里尝试实现的目标非常奇怪:为通过控制器输入的依赖注入注入的东西设置值并不是事情的方式通常都完成了。