Created
December 1, 2019 12:08
-
-
Save manne/50c887180e089b226e17b1c58a353337 to your computer and use it in GitHub Desktop.
Microsoft.Extensions.DependencyInjection Factory
This file contains hidden or 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
<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