Start of app, need to configure container. One option is to create a class to configure (register interfaces to implementations).
Benefits of Dependency Injection.
A) Unit testing. Can now mock implementations for interfaces. So instead of actually Saving data, it mocks a successful save. Instead of reading data, it mocks returned data. In the unit test, you can Verify that each call is done. Can check logged messages.
B) Able to change code implementations later. Without changing the "internal" code. Just change the container to register the interface to the new implementation (new class) ... existing code should work as is. This decoupling of code makes large applications very modular and flexible. It is now plug and play.
Types of DI:
1) Constructor Injection (most popular)
public class InjectedClass
{
private IDepInterface _iDependInterface;
public InjectedClass(IDepInterface myInterface)
{
_iDependInterface = myInterface;
}
}
2) Property Injection (applied at the property level)
private IDepInterface _myProp;
public IDepInterface MyDependencyProperty
{
get { return ths._myProp; }
set { this.myProp = value; }
}
3) Method Injection (when entire class doesn't need dependency, but just that one method)
public class InjectedClass
{
readonly IDepInterface _iDependencyInterface;
public MyMethod(IDepInterface myInterface)
{
// use myInterface
}
}
public class InjectedClass
{
private IDepInterface _iDependInterface;
public InjectedClass(IDepInterface myInterface)
{
_iDependInterface = myInterface;
}
}
2) Property Injection (applied at the property level)
private IDepInterface _myProp;
public IDepInterface MyDependencyProperty
{
get { return ths._myProp; }
set { this.myProp = value; }
}
3) Method Injection (when entire class doesn't need dependency, but just that one method)
public class InjectedClass
{
readonly IDepInterface _iDependencyInterface;
public MyMethod(IDepInterface myInterface)
{
// use myInterface
}
}