Benefits
By using dependency injection, you solve two main problems,1- Unit Test
2- Instantiation
Unit Test
You can resolve this by implementing interface of every class that is required to instantiated in any method or implementation. Always pass interface as parameter in constructor rather than making variables and instantiate in the class. For unit test, you can send mocked (the dummy) instantiation of that interface to that class.Before
public class Order{
public string ID { get; set; }
public string Detail { get; set; }
public void Process()
{
}
}
public class Cart
{
public void ProcessOrder()
{
Order order = new Order();
order.Process();
}
}
After
public interface IOrder
{
void Process();
}
public class Order : IOrder
{
public string ID { get; set; }
public string Detail { get; set; }
public void Process()
{
}
}
public class Cart
{
IOrder _order;
public Cart(IOrder order)
{
_order = order;
}
public void ProcessOrder()
{
_order.Process();
}
}
Now we are not bound to the instance of Order class. any thing passed in the Cart constructur that implements IOrder is accepted.
Instantiation
Use Autofac or any other Dependency Injection framework to register the types or instances. This will be added once e.g. for Console application, this can be added on Main method and in Web application, it will be added in global.asax file. More info about autofac is on link. Below is sample code for above example for dependency injection.
var builder = new ContainerBuilder();
// Register individual components
builder.RegisterInstance(new Order()).As<IOrder>();
builder.RegisterType<Cart>();
var container = builder.Build();
For MVC, we need to add Nuget package, Autofac.Integration.Mvc and for Web API, we need to add Autofac.Integration.WebApi
No comments:
Post a Comment