首页 > 解决方案 > 如何在 C# 中使用 IServiceCollection 将回调参数传递给我的服务类?

问题描述

首先,我想为我糟糕的英语道歉,因为我是中国人。我现在会尽力描述我的问题。如果您能耐心地阅读本文并给我一些建议,将不胜感激。

我打算用Microsoft.AspNetCore. 有一个带有名为的服务类的子项目,MyService用于ServiceCollectionExtensions添加MyServiceWebHostBuilder.

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

标签: c#asp.net

解决方案


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__


推荐阅读