【发布时间】:2018-09-26 14:07:49
【问题描述】:
我正在使用 EventFlow 来跟踪 ETW 事件。为此,我创建了一个充当侦听器的 ASP Net Core 服务。我已经在我的配置文件中配置了我自己的自定义输出。这些是我的 Output 和 OutputFactory 类:
class CustomOutput : IOutput
{
public Task SendEventsAsync(IReadOnlyCollection<EventData> events, long transmissionSequenceNumber, CancellationToken cancellationToken)
{
foreach(var e in events)
{
//...;
}
return Task.CompletedTask;
}
}
class CustomOutputFactory : IPipelineItemFactory<CustomOutput>
{
public CustomOutput CreateItem(IConfiguration configuration, IHealthReporter healthReporter)
{
return new CustomOutput();
}
}
此 CustomOutput 仅在启动时(创建 EventFlow 管道时)实例化一次,并用于所有事件。主要方法是这样的:
private static void Main()
{
try
{
using (var diagnosticsPipeline = ServiceFabricDiagnosticPipelineFactory.CreatePipeline("MyApplication-MyService-DiagnosticsPipeline"))
{
ServiceRuntime.RegisterServiceAsync("Stateless1Type",
context => new Stateless1(context)).GetAwaiter().GetResult();
ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(Stateless1).Name);
Thread.Sleep(Timeout.Infinite);
}
}
catch (Exception e)
{
ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString());
throw;
}
}
在配置文件eventFlowConfig.json中引用了输出和工厂输出类型:
"extensions": [
{
"category": "outputFactory",
"type": "CustomOutput",
"qualifiedTypeName": "MyProyect.Service.MyApp.SqlOutputFactory, MyProyect.Service.MyApp"
}
]
参考:Event aggregation and collection using EventFlow
因此,实例是在我的 Program 类的 main 方法中创建的,即在调用我的 Startup 配置方法之前。
如果容器在实例化时仍然不存在,我如何从我的输出类访问我的依赖容器服务?
目前,我创建了一个 IServiceCollection 类型的静态属性,并通过我的 Startup 配置方法(使用 setter 注入)对其进行了设置。我不喜欢这个解决方案,因为我不应该对服务使用静态访问,但我不知道其他解决方案。这是一种有效的做法吗?
class CustomOutput : IOutput
{
public static IServiceCollection Services { get; set; }
public Task SendEventsAsync(IReadOnlyCollection<EventData> events, long transmissionSequenceNumber, CancellationToken cancellationToken)
{
var sp = Services.BuildServiceProvider();
var loggerFactory = sp.GetService<ILoggerFactory>();
logger = loggerfactory.CreateLogger<CustomOutput>();
var repository = serviceProvider.GetService<IMyRepository>();
foreach (var e in events)
{
logger.LogDebug("event...");
repository.SaveEvent(e);
//...;
}
return Task.CompletedTask;
}
}
public class Startup
{
// Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//..
CustomOutput.Services = services;
//..
}
}
【问题讨论】:
-
IServiceCollection应该只构建一次。您在 for 循环中重复执行此操作。 -
显示更多关于需要哪些服务以及如何使用它们的详细信息。这可能是XY problem。
-
你说得对,IServiceCollection 一定是脱离了循环。使用具体服务更新帖子。
标签: c# asp.net-core dependency-injection azure-service-fabric event-flow