If you have no idea what DI is and what it's for, see this
Based on constructor dependencies injection
var config = new DiConfiguration();
//New call - new instance of SomeRepository
config.RegisterTransient<SomeRepository, SomeRepository>();
//New call - same instance of FirstProduct
config.RegisterSingleton<IProduct, FirstProduct>();
//Singleton, but with manual object creation - Singleton Instance
config.RegisterSingleton<IUser>(new User() { Balance = 5427 });
config.RegisterTransient<IProduct, FirstProduct>();
config.RegisterTransient<IProduct, SecondProduct>();
...
//This will return every implementation: FirstProduct, SecondProduct etc.
provider.Resolve<IEnumerable<IProduct>>();
//this will also work
config.RegisterTransient<IRepository, SomeRepository>();
config.RegisterTransient<IEnumerable<IRepository>, List<IRepository>>();
//returns List<IRepository>
provider.Resolve<IEnumerable<IRepository>>()
config.RegisterTransient<IRepository, SomeRepository>();
config.RegisterTransient(typeof(IService<>), typeof(SomeService<>));
//Fill parameters at runtime
provider.Resolve<IService<SomeRepository>>()
Let's say we have these two constructors:
public FirstProduct(IUser user)// FirstProduct implements IProduct
{
this.user = user;
}
public User(IProduct product)//User implements IUser
{
x = product;
}
We'll be unable to create user or product, because they rely on each other. To fix this, wrap either IUser or IProduct in Lazy class like this:
//creates with no issues
public User(Lazy<IProduct> product)
{
x = product;
}
Tip: If you're planning to use multiple containers as mentioned here , be sure to set DependencyProvider.Instance static field to desired provider before resolving dependency, despite it sets automatically after new object creation.
- Registering dependencies:
var config = new DiConfiguration();
config.RegisterTransient<Interface, Implementation>();
config.RegisterSingleton<Interface1, Implementation1>();
...
2.Creating Dependency Provider:
//should be created once in app lifecycle.
var provider = new DependencyProvider(config);
- Resolving dependencies:
var x = provider.Resolve<Interface>();
//x - Implementation.