如何在 Service Fabric 中使用 .NET Core 的内置依赖注入

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 class 和我的 DbContext class 上使用构造函数注入(通过 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

希望对您有所帮助。

这里已经回答了解决方案:

总而言之,您必须在创建无状态服务的新实例之前注册依赖项,然后创建工厂方法来解析依赖项:

即:

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();

有关详细信息,请参阅链接的答案。