Skip to content

Instantly share code, notes, and snippets.

@fatihdgn
Last active January 20, 2022 11:20
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 fatihdgn/d40fa1b6f7a3c34f8677bec9a42813fa to your computer and use it in GitHub Desktop.
Save fatihdgn/d40fa1b6f7a3c34f8677bec9a42813fa to your computer and use it in GitHub Desktop.
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