Skip to content

Instantly share code, notes, and snippets.

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 manne/50c887180e089b226e17b1c58a353337 to your computer and use it in GitHub Desktop.
Save manne/50c887180e089b226e17b1c58a353337 to your computer and use it in GitHub Desktop.
Microsoft.Extensions.DependencyInjection Factory
<Query Kind="Program">
<NuGetReference>Microsoft.Extensions.DependencyInjection</NuGetReference>
<NuGetReference>Microsoft.Extensions.DependencyInjection.Abstractions</NuGetReference>
<Namespace>Microsoft.Extensions.DependencyInjection</Namespace>
<Namespace>Microsoft.Extensions.DependencyInjection.Extensions</Namespace>
</Query>
void Main()
{
var sc = new ServiceCollection();
sc.AddSingleton<Test>();
sc.AddSingleton<TestLazy>();
sc.AddFactory<Car, CarFactory>();
sc.AddFactory<Airplane, AirplaneFactory>();
sc.BuildServiceProvider().GetService<Test>().Dump();
sc.BuildServiceProvider().GetService<TestLazy>().Dump();
}
public static class ServiceCollectionExtensions
{
public static void AddFactory<TImplementation, TFactory>(this IServiceCollection services)
where TFactory : class, IFactory<TImplementation>
where TImplementation : class
{
services.AddSingleton<IFactory<TImplementation>, TFactory>();
services.AddSingleton<TImplementation>(x =>
x.GetRequiredService<IFactory<TImplementation>>().Create()
);
services.AddSingleton<Func<TImplementation>>(x => () => x.GetRequiredService<IFactory<TImplementation>>().Create());
}
}
public class Test
{
public Test(Car aa, Airplane bb)
{
Car = aa;
Airplane = bb;
}
public Car Car {get; }
public Airplane Airplane {get; }
}
public class TestLazy
{
public TestLazy(Func<Car> aa, Airplane bb)
{
Car = aa();
Airplane = bb;
}
public Car Car { get; }
public Airplane Airplane { get; }
}
public interface IFactory<T>
{
T Create();
}
public class Car
{
public Car(string name)
{
Name = name;
}
public string Name { get; }
}
public class CarFactory : IFactory<Car>
{
public Car Create() => new Car("aaa");
}
public class Airplane
{
public Airplane(string name)
{
Name = name;
}
public string Name { get; }
}
public class AirplaneFactory : IFactory<Airplane>
{
public Airplane Create() => new Airplane("Airplaneeeeeee");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment