c# - 如何在 Service Fabric 中使用 .NET Core 的内置依赖注入(inject)

标签 c# .net-core azure-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 类上使用构造函数注入(inject)(通过 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 文件,但我似乎无法弄清楚!任何帮助将不胜感激。

最佳答案

这里已经回答了解决方案:Set up Dependency Injection on Service Fabric using default ASP.NET Core DI container

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

即:

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

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

关于c# - 如何在 Service Fabric 中使用 .NET Core 的内置依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54696048/

相关文章:

unit-testing - 测试 FabricClient 对象

javascript - 将 javascript 值传递给 C# 值

c# - 执行时 ASP.Net MVC "Could Not Load Type"

c# - 测试/模拟什么?

C# 在 #if DEBUG 中使用语句但不运送程序集

linux - Dotnet Core 将不会使用交换

c# - dotnetcore GetTypeInfo() 没有在类型对象的变量上定义?

azure-devops - 生成依赖片段文件任务失败

C# X509 证书验证,具有在线 CRL 检查,无需将根证书导入受信任的根 CA 证书存储

c# - 以编程方式创建应用程序和服务