Skip to content

Instantly share code, notes, and snippets.

@stevejgordon
Last active October 20, 2023 11:59
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevejgordon/17313b24bfbd3bd3277363e6cabfd898 to your computer and use it in GitHub Desktop.
Save stevejgordon/17313b24bfbd3bd3277363e6cabfd898 to your computer and use it in GitHub Desktop.
<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