Created
November 8, 2018 19:31
-
-
Save henkmollema/1d75be0116fb8da80fded14dbebe81eb to your computer and use it in GitHub Desktop.
Consuming transient services from singletons
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class BarService | |
{ | |
public DateTime Now { get; } = DateTime.UtcNow; | |
} | |
public class FooService | |
{ | |
private readonly BarService _barService; | |
public FooService(BarService barService) | |
{ | |
_barService = barService; | |
} | |
public string PrintDate() => _barService.Now.ToString("dd-MM-yyyy HH:mm:ss:ffff"); | |
} | |
public class Startup | |
{ | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
services.AddSingleton<FooService>(); | |
// This turns BarService into a singleton | |
services.AddTransient<BarService>(); | |
// This would cause resolving FooService to throw an exception (as expected) | |
//services.AddScoped<BarService>(); | |
} | |
public void Configure(IApplicationBuilder app, IHostingEnvironment env) | |
{ | |
app.Run(async (context) => | |
{ | |
try | |
{ | |
var fooService = context.RequestServices.GetRequiredService<FooService>(); | |
await context.Response.WriteAsync("Hello World: " + fooService.PrintDate()); | |
} | |
catch (Exception ex) | |
{ | |
await context.Response.WriteAsync(ex.ToString()); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment