簡體   English   中英

如何使用 C# 中的 IServiceCollection 將回調參數傳遞給我的服務 class?

[英]How to pass a callback parameter to my service class with IServiceCollection in C#?

首先,我想為我糟糕的英語道歉,因為我是中國人。 我現在會盡力描述我的問題。 如果您能耐心地閱讀本文並給我一些建議,將不勝感激。

我將使用Microsoft.AspNetCore開發一個 Web 應用程序。 有一個子項目,其中包含名為MyService的服務 class 和用於將MyService添加到WebHostBuilderServiceCollectionExtensions

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 class的構造函數?

addScoped 方法有一些重載,其中一個是創建服務實例的工廠,因此您可以使用該重載並傳入您創建的工廠,並在工廠定義中添加傳遞您的服務構造函數中的回調。 You will find more details here 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__

編寫擴展方法如下:

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddMyService(this IServiceCollection services, Func<RequestContext> callBack = null)
    {
        services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        services.AddScoped<IMyService, MyService>(sp => new MyService(new HttpContextAccessor(), new Func<RequestContext>(target)));

        return services;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM