问题描述
我想使用 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 func 完成之前返回?
I think this question will give you some light: Why does ServiceRuntime.RegisterServiceAsync return before the serviceFactory func completes?
技术上,ServiceRuntime.RegisterServiceAsync()
是一个依赖注册,它需要你传递serviceTypeName和负责创建服务的工厂方法Func服务工厂
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();
附注:
- 永远不要在 DI 中注册上下文 (StatelessServiceContextStatefulServiceContext),在共享进程方法中,多个分区可能托管在同一个进程上,并且会有多个上下文.
- 此代码片段未经测试,我过去使用过,无权验证是否匹配相同的代码,但与使用的方法非常接近,可能需要一些调整.
这篇关于使用默认的 ASP.NET Core DI 容器在 Service Fabric 上设置依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!