-
-
Save stevejgordon/17313b24bfbd3bd3277363e6cabfd898 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
<Project Sdk="Microsoft.NET.Sdk"> | |
<PropertyGroup> | |
<OutputType>Exe</OutputType> | |
<TargetFramework>net5.0</TargetFramework> | |
</PropertyGroup> | |
<ItemGroup> | |
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="5.0.1" /> | |
</ItemGroup> | |
</Project> |
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
using System; | |
using Microsoft.Extensions.DependencyInjection; | |
namespace DependencyInjectPlayground | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
// See https://www.stevejgordon.co.uk/aspnet-core-dependency-injection-what-is-the-iservicecollection | |
var serviceCollection = new ServiceCollection(); | |
serviceCollection.AddSingleton<ClassA>(); | |
serviceCollection.AddSingleton<IThing, ClassB>(); | |
// See https://www.stevejgordon.co.uk/aspnet-core-dependency-injection-what-is-the-iserviceprovider-and-how-is-it-built | |
var serviceProvider = serviceCollection.BuildServiceProvider(); | |
Console.WriteLine("Done"); | |
} | |
} | |
public interface IThing | |
{ | |
public void DoStuff(); | |
} | |
public class ClassA | |
{ | |
private readonly IThing _dependency; | |
public ClassA(IThing thing) => _dependency = thing; | |
public void DoWork() => _dependency.DoStuff(); | |
} | |
public class ClassB : IThing | |
{ | |
public void DoStuff() | |
{ | |
// Imagine implementation | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment