Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<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>
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