下午好,
我最近开始尝试使用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类上(通过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文件,但似乎无法弄清楚!任何帮助将不胜感激。
答案 0 :(得分:0)
TaeSeo
我认为您正在寻找的内容已在我正在研究的项目-CoherentSolutions.Extensions.Hosting.ServiceFabric中实现。
在 CoherentSolutions.Extensions.Hosting.ServiceFabric 方面,您需要的内容如下:
private static void Main(string[] args)
{
new HostBuilder()
.DefineStatelessService(
serviceBuilder => {
serviceBuilder
.UseServiceType("ServiceName")
.DefineDelegate(
delegateBuilder => {
delegateBuilder.ConfigureDependencies(
dependencies => {
dependencies.AddScoped<FaxLogic>();
});
delegateBuilder.UseDelegate(
async (StatelessServiceContext context, FaxLogic faxLogic) => {
while (true) {
cancellationToken.ThrowIfCancellationRequested();
ServiceEventSource.Current.ServiceMessage(context, "Hello!");
await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken);
});
})
})
.Build()
.Run();
}
如果您还有其他问题,请随时提出或检查项目wiki
希望有帮助。
答案 1 :(得分:0)
解决方案已在此处得到解答: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();
有关更多详细信息,请参见链接的答案。