15 Satırda IoC Container

Bu yazımda IoC ile ilgili pek fazla detaya girmeyeceğim, bunu daha sonra telafi eder burayı da güncellerim.
Geçenlerde alternatif IoC container paketleri bulmaya çalışırken Scott Hanselman’ın yazısına denk geldim. Dikkatimi çeken altlarda listelenen Oren Eini‘nin ve Ken Egozi‘nin DIY (Do It Yourself) olanları oldu. Ben de bir deneyeyim bakalım diye düşündüm ve sonuç aşağıda;

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;
}
view raw Container.cs hosted with ❤ by GitHub

Daha sonra görüşmek üzere…

Start typing and press Enter to search

X