Last active
April 8, 2022 19:18
-
-
Save CraftyFella/a29efd9ce6b71cc3fecabfb6de542e0e to your computer and use it in GitHub Desktop.
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
// See https://aka.ms/new-console-template for more information | |
using Microsoft.Extensions.DependencyInjection; | |
using Microsoft.Extensions.Hosting; | |
public static class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
var build = CreateHostBuilder(args).Build(); | |
var thing = build.Services.GetRequiredService<Thing>(); | |
var thing2 = build.Services.GetRequiredService<Thing>(); | |
Console.WriteLine(thing.Equals(thing2)); | |
build.Run(); | |
} | |
public static IHostBuilder CreateHostBuilder(string[] args) => | |
Host.CreateDefaultBuilder(args) | |
.ConfigureServices(builder => | |
{ | |
builder.AddSingleton(sp => | |
{ | |
Console.WriteLine("In in the factory"); | |
return new Thing(); | |
}); | |
}); | |
} | |
public class Thing | |
{ | |
public Thing() | |
{ | |
Console.WriteLine("I'm being created"); | |
} | |
} | |
// Output | |
// In in the factory | |
// I'm being created | |
// True | |
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
// See https://aka.ms/new-console-template for more information | |
using Microsoft.Extensions.DependencyInjection; | |
using Microsoft.Extensions.Hosting; | |
public static class Program | |
{ | |
public static async Task Main(string[] args) | |
{ | |
var build = CreateHostBuilder(args).Build(); | |
var thing = Task.Run(() => build.Services.GetRequiredService<Thing>()); | |
var thing2 = Task.Run(() => build.Services.GetRequiredService<Thing>()); | |
var whenAll = await Task.WhenAll(thing, thing2); | |
Console.WriteLine(whenAll[0].Equals(whenAll[1])); | |
build.Run(); | |
} | |
public static IHostBuilder CreateHostBuilder(string[] args) => | |
Host.CreateDefaultBuilder(args) | |
.ConfigureServices(builder => | |
{ | |
builder.AddSingleton(sp => | |
{ | |
Console.WriteLine("In in the factory"); | |
Thread.Sleep(3000); | |
return new Thing(); | |
}); | |
}); | |
} | |
public class Thing | |
{ | |
public Thing() | |
{ | |
Console.WriteLine("I'm being created"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment