Last active
January 20, 2022 11:20
-
-
Save fatihdgn/d40fa1b6f7a3c34f8677bec9a42813fa to your computer and use it in GitHub Desktop.
This file contains 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
public class Container | |
{ | |
Dictionary<Type, Func<Container, object>> factory; | |
public Container() | |
{ | |
factory = new Dictionary<Type, Func<Container, object>>(); | |
} | |
public void Register<TReferenceType, TObjectType>(Func<Container, TObjectType> creator = null) | |
where TObjectType : TReferenceType | |
{ | |
if (creator == null) creator = c => (TObjectType)Activator.CreateInstance(typeof(TObjectType)); | |
factory.Add(typeof(TReferenceType), c => creator.Invoke(c)); | |
} | |
public object Create(Type type) => factory[type]?.Invoke(this); | |
public TReferenceType Create<TReferenceType>() => (TReferenceType)Create(typeof(TReferenceType)); | |
static Lazy<Container> instance = new Lazy<Container>(); | |
public static Container Instance => instance.Value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment