c# - 如何在 C# 中使用 IServiceCollection 将回调参数传递给我的服务类?
问题描述
首先,我想为我糟糕的英语道歉,因为我是中国人。我现在会尽力描述我的问题。如果您能耐心地阅读本文并给我一些建议,将不胜感激。
我打算用Microsoft.AspNetCore
. 有一个带有名为的服务类的子项目,MyService
用于ServiceCollectionExtensions
添加MyService
到WebHostBuilder
.
public class MyService: IMyService
{
public MyService(IHttpContextAccessor httpContextAccessor, Func<RequestContext> callBack = null)
{
_httpContextAccessor = httpContextAccessor;
_callBack = callBack;
}
}
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddMyService(this IServiceCollection services, Func<RequestContext> callBack = null)
{
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// TODO: pass callBack function to the constructor of MyService
return services.AddScoped<IMyService, MyService>();
}
}
所以我的问题是如何将 callBack 参数传递给类的构造函数MyService
?
解决方案
addScoped 方法有一些重载,其中一个是创建服务实例的工厂,因此您可以使用该重载并传入您创建的工厂,并在工厂定义中添加传递您的服务构造函数中的回调。您将在此处找到更多详细信息 https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.servicecollectionserviceextensions.addscoped?view=aspnetcore-3.0#Microsoft_Extensions_DependencyInjection_ServiceCollectionServiceExtensions_AddScoped_Microsoft_Extensions_DependencyInjection_IServiceCollection_System_Type_System_Func_System_IServiceProvider_System_Object__
推荐阅读
- android - Google Fit - 与 Google Play 服务的连接丢失
- c# - 在 word addin 中查找并突出显示问题
- oracle - Oracle OCCI 无法正确检索小数点后的值
- c++ - 无法在 Visual Studio 和 vcpkg 中构建 cmake 项目(致命错误 C1083)
- angular - 在 ionic 3 中将 QR 码发送到电子邮件
- angular - 使用元素名称将属性绑定到元素的子元素 | 角 5
- php - 如何检查第一个 $_GET 的值并打印或检查第二个并打印值是否不同?
- python - 如何使用 pandas 解析嵌套 json 中的选定值
- php - Symfony 将子域定向到路由
- angular - Angular 2 Web 应用程序与本地 ADFS 2.0 集成