使用默认的ASP.NET Core DI容器在Service Fabric上设置依赖项注入 [英] Set up Dependency Injection on Service Fabric using default ASP.NET Core DI container

查看:96
本文介绍了使用默认的ASP.NET Core DI容器在Service Fabric上设置依赖项注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to use ASP.NET Core's default DI container to setup DI for my Service Fabric project.

//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 类对 ConfigProvider 类具有依赖性,则设置DI,例如:

How would I set up DI, if MyMonitor class has a dependency on a ConfigProvider class, like this:

public MyMonitor(IConfigProvider configProvider)
{
  this._configProvider = configProvider;
}


推荐答案

我认为这个问题会给您一些启示:为什么ServiceRuntime.RegisterServiceAsync在serviceFactory函数完成之前返回?

I think this question will give you some light: Why does ServiceRuntime.RegisterServiceAsync return before the serviceFactory func completes?

从技术上讲, ServiceRuntime.RegisterServiceAsync()是依赖项注册,它要求您传递serviceTypeName和负责创建服务的工厂方法。 < StatelessServiceContext,StatelessService> serviceFactory

Technically, the ServiceRuntime.RegisterServiceAsync() is a dependency registration, it requires you to pass the serviceTypeName and the factory method responsible for creating the services Func<StatelessServiceContext, StatelessService> serviceFactory

工厂方法接收上下文并返回服务(有状态或无状态)。

The factory method receives the context and returns a service (Stateful or stateless).

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

For DI, you should register all dependencies in advance and call resolve services to create the constructor, something like:

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:



  • 切勿在DI中注册上下文(StatelessServiceContext\StatefulServiceContext),采用共享过程方法,多个分区可能托管在同一进程上,并且将拥有多个上下文。

  • 此代码段未经过测试,我过去使用过,无权验证是否匹配相同的代码,但可能与所使用的方法非常接近需要一些调整。

  • 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.

这篇关于使用默认的ASP.NET Core DI容器在Service Fabric上设置依赖项注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆