Skip to content

Instantly share code, notes, and snippets.

@henkmollema
Created November 8, 2018 19:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save henkmollema/1d75be0116fb8da80fded14dbebe81eb to your computer and use it in GitHub Desktop.
Save henkmollema/1d75be0116fb8da80fded14dbebe81eb to your computer and use it in GitHub Desktop.
Consuming transient services from singletons
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