依赖关系注入的解析速度不够快,无法在服务依赖于另一个服务时使用



我正在将两个服务注入我的点网核心Web api,主要服务依赖于帮助程序服务中的数据。 帮助程序服务在构造函数中填充此数据,但是当主服务使用此数据时,它尚未准备就绪,因为帮助程序服务的构造函数在需要时尚未完成。

我认为 DI 和编译器会正确解析和链接这些服务,因此在完全实例化之前不会使用帮助程序服务。

如何告诉主服务等到帮助程序服务完全解析并实例化?

我正在做的事情的通用示例代码。 我在 MainSerice 中调用 DoSomething((,HelperService 调用外部 API 以获取一些数据,该数据在 MainService 中是必需的。

启动.cs

public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IHelperService, HelperService);
services.Scoped<IMainService, MainService);
}

主服务.cs

public class MainService : IMainService
{
private readonly IHelperServuce _helper;
public MainService(IHelperService HelperService)
{
_helper = HelperService;
}
public void DoSomething()
{   
string helperParameter = _helper.Param1; //This fails because the constructor of HelperService has not finished 
}
}

助手服务.cs

public class HelperService : IHelperService
{
public HelperService()
{
GetParamData();
}
private async void GetParamData()
{
var response = await CallExternalAPIForParameters(); //This may take a second.
Params1 = response.value;
}

private string _param1;
public string Param1
{
get
{
return _param1;
}
private set
{
_param1 = value;
}
}
}

您没有等待构造函数中GetParamData()数据的异步方法。当然,这是不可能的。构造函数应仅初始化简单数据。您可以通过以下方式解决此问题,而不是使用属性返回,您还可以从名为(例如(Task<string> GetParam1()的方法返回 Task。这可以缓存字符串值。

例如:

public class HelperService : IHelperService
{
private string _param1;
// note: this is not threadsafe.
public async Task<string> GetParam1()
{
if(_param1 != null)
return _param1;
var response = await CallExternalAPIForParameters(); //This may take a second.
_params1 = response.value;
return _param1;
}
}

您甚至可以返回ValueTask<string>因为大多数调用都可以同步执行。

将 lambda 传递给在主服务中初始化变量的帮助程序服务,如...

Helper service.getfirstparam(  (response) -> 
{  firstparam = response.data;});
While (firstparam == null)
sleep
// now do your processing

最新更新