问题描述
我想使用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;
}
推荐答案
我认为这个问题会给您一些启示:
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:
这篇关于使用默认的ASP.NET Core DI容器在Service Fabric上设置依赖项注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!