dependency-injection - 使用默认 ASP.NET Core DI 容器在 Service Fabric 上设置依赖注入(inject)

标签 dependency-injection .net-core azure-service-fabric

我想使用 ASP.NET Core 的默认 DI 容器为我的 Service Fabric 项目设置 DI。

//This is what I've got so far, and it works great
ServiceRuntime.RegisterServiceAsync(
  "MyServiceType",
  context => new MyService(context, new MyMonitor()
).GetAwaiter().GetResult();

//This is how I use it
public MyService(StatefulServiceContext context, IMonitor myMonitor)
  : base(context)
{
  this._myMonitor = myMonitor;           
}

如果 MyMonitor,我将如何设置 DI类依赖于 ConfigProvider类,像这样:
public MyMonitor(IConfigProvider configProvider)
{
  this._configProvider = configProvider;
}

最佳答案

我想这个问题会给你一些启示:Why does ServiceRuntime.RegisterServiceAsync return before the serviceFactory func completes?

从技术上讲,ServiceRuntime.RegisterServiceAsync()是一个依赖注册,它需要你传递 serviceTypeName 和负责创建服务的工厂方法 Func<StatelessServiceContext, StatelessService> serviceFactory
工厂方法接收上下文并返回服务(有状态或无状态)。

对于 DI,您应该提前注册所有依赖项并调用解析服务来创建构造函数,例如:

var provider = new ServiceCollection()
            .AddLogging()
            .AddSingleton<IFooService, FooService>()
            .AddSingleton<IMonitor, MyMonitor>()
            .BuildServiceProvider();

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

PS:

  • Never Register the context (StatelessServiceContext\StatefulServiceContext) in the DI, in a shared process approach, multiple partitions might be hosted on same process and will ahve multiple contexts.
  • This code snippet is not tested, I've used in the past, don't have access to validate if matches the same code, but is very close to the approach used, might need some tweaks.

关于dependency-injection - 使用默认 ASP.NET Core DI 容器在 Service Fabric 上设置依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54185571/

相关文章:

c# - 在多个配置文件中重新定义 spring.net 对象

linq-to-sql - 将 Linq 到 SQL 代码迁移到 .Net Core

azure-service-fabric - Azure Service Fabric 成本计算,节点与实例

ssl - 本地 Service Fabric 使用第三方 CA 证书的安全集群

c# - ASP.NET Core DI 构造函数与 RequestServices

asp.net-web-api - 构造函数依赖注入(inject) WebApi 属性

asp.net - Dotnet Core 从 Mac 发布到 IIS

c# - .NET Core 1.1 控制台应用程序总是在 Ubuntu 16.04 上作为 systemd 服务退出/崩溃

azure - Azure Service Fabric 中的主节点和非主节点有什么区别?

c# - ASP.NET Web Api 依赖注入(inject)——单例与否