Skip to content

Instantly share code, notes, and snippets.

@jbrestan
Forked from davidfowl/PureDI.cs
Last active January 20, 2020 10:44
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 jbrestan/b346a98078fd81cbad4c89c2b35c3914 to your computer and use it in GitHub Desktop.
Save jbrestan/b346a98078fd81cbad4c89c2b35c3914 to your computer and use it in GitHub Desktop.
Modified from: DI under the hood. This is what DI containers automate for you.
using System;
using System.Threading;
namespace PureDI
{
class Program
{
static void Main(string[] args)
{
// Create the singletons once
var singleton2 = new Singleton2();
var singleton1 = new Singleton1(singleton2);
// Create a transient object
var myClass = new MyTransientClass1(
singleton1,
singleton2,
new MyTransientClass2(
new MyTransientClass3()));
// Create another transient object
var otherClass = new MyTransientClass2(new MyTransientClass3());
}
static void WebRequest(Func<Scoped1> scoped1Factory)
{
var scoped1 = scoped1Factory();
// Create a controller passing the request scoped dependency
var controller = new MyController(scoped1);
}
}
public class MyController
{
public IScoped1 Scoped1 { get; }
public MyController(IScoped1 scoped1)
{
Scoped1 = scoped1;
}
}
// Transient dependencies
public interface IMyTransientClass1 { }
public interface IMyTransientClass2 { }
public interface IMyTransientClass3 { }
public class MyTransientClass1 : IMyTransientClass1
{
public ISingleton1 Singleton1 { get; }
public ISingleton2 Singleton2 { get; }
public IMyTransientClass2 MyTransientClass2 { get; }
public MyTransientClass1(ISingleton1 singleton1, ISingleton2 singleton2, IMyTransientClass2 myOtherClass)
{
Singleton1 = singleton1;
Singleton2 = singleton2;
MyTransientClass2 = myOtherClass;
}
}
public class MyTransientClass2 : IMyTransientClass2
{
public IMyTransientClass3 MyTransientClass3 { get; }
public MyTransientClass2(IMyTransientClass3 anotherClass)
{
MyTransientClass3 = anotherClass;
}
}
public class MyTransientClass3 : IMyTransientClass3
{
}
// Scoped dependencies
public interface IScoped1 { }
public class Scoped1 : IScoped1
{
}
// Singleton dependencies
public interface ISingleton1 { }
public interface ISingleton2 { }
public class Singleton1 : ISingleton1
{
public ISingleton2 Singleton2 { get; }
public Singleton1(ISingleton2 singleton2)
{
Singleton2 = singleton2;
}
}
public class Singleton2 : ISingleton2 { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment