Welcome to XirzoDIContainer! This is a lightweight Dependency Injection (DI) library designed to simplify dependency management in your C# applications. 🚀
- Type Binding: Bind concrete types directly with
BindType<T>()
🎯 - Interface Binding: Map interfaces to implementations using
Bind<T>().To<TImplementation>()
🔄 - Instance Binding: Bind existing instances using
ToInstance()
📦 - Factory Binding: Create custom instantiation logic with
ToFactory()
🏭 - Lifetime Management:
- Singleton: One instance for all resolutions
- Transient: New instance per resolution
- Fluent API: Intuitive and chainable configuration methods 🔗
- Create your container:
var container = new ContainerDi();
- Register your dependencies:
// Singleton
container.BindType<MyService>()
.AsSingleton();
// Transient
container.BindType<MyService>()
.AsTransient();
// Singleton
container.Bind<IMyService>()
.To<MyService>()
.AsSingleton();
// Transient
container.Bind<IMyService>()
.To<MyService>()
.AsTransient();
var myInstance = new MyService();
container.Bind<IMyService>()
.ToInstance(myInstance);
container.Bind<IMyService>()
.ToFactory(() => new MyService());
// Resolve your service
var service = container.Resolve<IMyService>();
-
Singleton vs Transient:
- Use
AsSingleton()
when you need the same instance throughout your application - Use
AsTransient()
when you need a new instance each time
- Use
-
Instance Binding:
- Use
ToInstance()
when you have pre-configured instances - Note: You cannot bind multiple instances to the same type
- Use
-
Factory Binding:
- Use
ToFactory()
when you need custom instantiation logic - Factories always create new instances
- Use
public interface IGreetingService
{
void Greet();
}
public class GreetingService : IGreetingService
{
public void Greet()
{
Console.WriteLine("Hello!");
}
}
// Setup container
var container = new ContainerDi();
// Register as singleton
container.Bind<IGreetingService>()
.To<GreetingService>()
.AsSingleton();
// Resolve and use
var service = container.Resolve<IGreetingService>();
service.Greet();