簡體   English   中英

如何將.NET Core的內置依賴注入與Service Fabric結合使用

[英]How to use .NET Core's Built in Dependency Injection with Service Fabric

下午好,

我最近開始嘗試使用Service Fabric和.NET Core。 我創建了一個無狀態Web API,並使用以下命令執行了一些DI:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    var connString = Configuration.GetConnectionString("DefaultConnection");
    services.AddScoped<FaxLogic>();
    services.AddDbContext<ApplicationContext>(options => options.UseSqlServer(connString));
}

通過上面的內容,我可以對我的FaxLogic類和DbContext類(通過FaxLogic)使用構造函數注入:

private readonly FaxLogic _faxLogic;
public FaxController(
    FaxLogic faxLogic)
{
    _faxLogic = faxLogic;
}
private readonly ApplicationContext _context;
public FaxLogic(ApplicationContext context)
{
    _context = context;
}

然后,我創建了一個非Web API無狀態服務。 我希望能夠像在WebAPI中一樣訪問我的FaxLogic和DbContext,但是在無狀態服務的RunAsync方法中:

protected override async Task RunAsync(CancellationToken cancellationToken)
{
    // TODO: Replace the following sample code with your own logic 
    //       or remove this RunAsync override if it's not needed in your service.

    while (true)
    {
        cancellationToken.ThrowIfCancellationRequested();

        ServiceEventSource.Current.ServiceMessage(this.Context, "Hello!");

        // do db stuff here!

        await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken);
    }
}

我想知道我會怎么做。 我嘗試使用CreateServiceInstanceListeners()方法和使用ServiceRuntime進行注冊的Program.cs文件,但似乎無法弄清楚! 任何幫助,將不勝感激。

泰熙

我認為您正在尋找的內容已在我正在工作的項目中實現-CoherentSolutions.Extensions.Hosting.ServiceFabric

CoherentSolutions.Extensions.Hosting.ServiceFabric方面,您要查找的內容如下所示:

private static void Main(string[] args)
{
  new HostBuilder()
    .DefineStatelessService(
      serviceBuilder => {
        serviceBuilder
          .UseServiceType("ServiceName")
          .DefineDelegate(
            delegateBuilder => {
              delegateBuilder.ConfigureDependencies(
                dependencies => {
                  dependencies.AddScoped<FaxLogic>();
                });
              delegateBuilder.UseDelegate(
                async (StatelessServiceContext context, FaxLogic faxLogic) => {
                  while (true) {
                    cancellationToken.ThrowIfCancellationRequested();

                    ServiceEventSource.Current.ServiceMessage(context, "Hello!");

                    await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken);
                });
            })
       })
    .Build()
    .Run();
}

如果您還有其他問題,請隨時詢問或查看項目Wiki。

希望能幫助到你。

解決方案已在此處得到解答: 使用默認ASP.NET Core DI容器在Service Fabric上設置依賴項注入

總而言之,您必須先注冊依賴項,然后才能創建無狀態服務的新實例,然后創建工廠方法來解決依賴項:

即:

public static class Program
{
    public static void Main(string[] args)
    {
        var provider = new ServiceCollection()
                    .AddLogging()
                    .AddSingleton<IFooService, FooService>()
                    .AddSingleton<IMonitor, MyMonitor>()
                    .BuildServiceProvider();

        ServiceRuntime.RegisterServiceAsync("MyServiceType",
            context => new MyService(context, provider.GetService<IMonitor>());
        }).GetAwaiter().GetResult();

有關更多詳細信息,請參見鏈接的答案。

暫無
暫無

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

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