public static CSharpKernel UseAspNetCore(this CSharpKernel kernel) { InteractiveHost interactiveHost = null; var directive = new Command("#!aspnet", "Activate ASP.NET Core") { Handler = CommandHandler.Create(async() => { if (interactiveHost is {}) { return; } var interactiveLoggerProvider = new InteractiveLoggerProvider(); kernel.AddMiddleware(async(command, context, next) => { // REVIEW: Is there a way to log even when there's no command in progress? // This is currently necessary because the #!log command uses KernelInvocationContext.Current in // its LogEvents.Subscribe callback and KernelInvocationContext.Current is backed by an AsyncLocal. // Is there a way to log to diagnostic output without KernelInvocationContext.Current? using (command is SubmitCode ? interactiveLoggerProvider.SubscribePocketLogerWithCurrentEC() : null) { await next(command, context).ConfigureAwait(false); } }); // The middleware doesn't cover the current command's executions so we need this to capture startup logs. using (interactiveLoggerProvider.SubscribePocketLogerWithCurrentEC()) { // We could try to manage the host's lifetime, but for now just stop the kernel if you want to stop the host. interactiveHost = new InteractiveHost(interactiveLoggerProvider); var startHostTask = interactiveHost.StartAsync(); var rDirectives = string.Join(Environment.NewLine, _references.Select(a => $"#r \"{a.Location}\"")); var usings = string.Join(Environment.NewLine, _namespaces.Select(ns => $"using {ns};")); await kernel.SendAsync(new SubmitCode($"{rDirectives}{Environment.NewLine}{usings}"), CancellationToken.None).ConfigureAwait(false); await startHostTask.ConfigureAwait(false); var httpClient = HttpClientFormatter.CreateEnhancedHttpClient(interactiveHost.Address, interactiveLoggerProvider); await kernel.SetValueAsync <IApplicationBuilder>("App", interactiveHost.App).ConfigureAwait(false); await kernel.SetValueAsync <IEndpointRouteBuilder>("Endpoints", interactiveHost.Endpoints).ConfigureAwait(false); await kernel.SetValueAsync <HttpClient>("HttpClient", httpClient).ConfigureAwait(false); } }) };
public InteractiveHost(InteractiveLoggerProvider interactiveLoggerProvider) { _interactiveLoggerProvider = interactiveLoggerProvider; _startup = new Startup(); Environment.SetEnvironmentVariable($"ASPNETCORE_{WebHostDefaults.PreventHostingStartupKey}", "true"); var hostBuilder = Host.CreateDefaultBuilder() .ConfigureWebHostDefaults(webBuilder => webBuilder .ConfigureKestrel(kestrelOptions => kestrelOptions.Listen(IPAddress.Loopback, 0)) .UseStartup(_ => _startup)) .ConfigureLogging(loggingBuilder => loggingBuilder .SetMinimumLevel(LogLevel.Trace) .ClearProviders() .AddProvider(_interactiveLoggerProvider)); _host = hostBuilder.Build(); }
public InteractiveLogger(InteractiveLoggerProvider loggerProvider, string categoryName) { _loggerProvider = loggerProvider; _categoryName = categoryName; }