Injection Dependence and Using the Default Constructor

I am trying to understand the concept of Injection Dependency. Below is an example that I am trying to debug. Here I created the Customer class, whose dependencies I have Injected in its constructor. Now that I have called this.Iorder.GetOrderDetails(); in the Index method, he gave me a NullReferenceException error and asked me to use the new keyword to create an object to call the method. When I moved this call to this.Iorder.GetOrderDetails(); to another method GetCutomerDetails() and called this method in the index method, it works.

Question I can’t understand why the call to the this.Iorder.GetOrderDetails() method does not work in the Index method and why it works in GetCutomerDetails()

 public interface IorderDetails { void GetOrderDetails(); } public class CustomerModel : IorderDetails { public void GetOrderDetails() {} } 

Controller:

 public class CustomerController: Controller { private IorderDetails Iorder; //DI constructor Injecting OrderDetails object CustomerController(IorderDetails iorderObj) { if (iorderObj == null) throw new ArgumentNullException("orderObj should not be null"); this.Iorder = iorderObj; } //Default constructor public CustomerController() { } public ActionResult Index() { CustomerController objCustomer = new CustomerController(new CustomerModel()); objCustomer.GetCutomerDetails(); //Commented GetOrderDetails() method //this.Iorder.GetOrderDetails(); return View(); } public ActionResult GetCutomerDetails() { this.Iorder.GetOrderDetails(); return View(); } } 
+4
source share
1 answer

You have a default constructor for CustomerController . When it is called, you do not assign anything to Iorder . So in this case it is null . After that, in the Index() method, you try to execute the GetOrderDetails() method using Iorder , which is null. It fails. When you create another instance of CustomerController inside the Index() method, you can call GetOrderDetails() on that instance.

In general, using multiple constructors is not recommended in conjunction with Injection Dependency. But when necessary, you must initialize all instance fields with what works. This is called the local default. Great book on dependency dependency patterns and anti-patterns. Injecting dependencies in .NET . Also take a look at your author’s blog.

+2
source

All Articles