Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have been using option 2 below to refactor some legacy code. However, I have seen a lot of people doing injection using option 1. Can someone help me review the code below and let me know if there is any issue with what am doing? Both of these options make the "repository" available to all Action Results within the controller. Your input is appreciated.

Code:

Public interface ICustomerRepository
{
void Insert(Customer obj);
...
}

Public class CustomerRepository:ICustomerRepository
{
 Public void Insert(Customer obj)
 {
  ... 
 }
}

Controller usage - option 1:

Public class CustomerController : Controller
{
 private ICustomerRepository repository = null;
 public CustomerController()
 {
  this.repository = new CustomerRepository();
 } 
 public CustomerController(ICustomerRepository repository)
 {
  this.repository = repository;
 } 
 public ActionResult Insert(Customer obj)
 {
  repository.Insert(obj);
  ...
 }
}

Controller usage - option 2:

Public class CustomerController : Controller
{
 ICustomerRepository repository = new CustomerRepository();
 public ActionResult Insert(Customer obj)
 {
  repository.Insert(obj);
  ...
 }
}
share|improve this question

put on hold as off-topic by Malachi, 200_success 16 hours ago

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

2  
Both options leave you with a hardwired dependency on the repository and are exactly the same; initializing in the constructor or statically at declaration site is exactly the same. I suggest you read up on Dependency Injection - constructor-injecting an abstraction would be a radically different alternative... but none of that has anything to do with the repository pattern. Feel free to implement a working solution, we'll gladly review it and help you improve. –  Mat's Mug 15 hours ago
1  
Oh gosh, I only saw the default/parameterless constructor! By removing the hard-coded default and leaving only the parameterized constructor, you are injecting an abstraction, and coding against that - so go with option 1, but ditch the parameterless constructor. –  Mat's Mug 14 hours ago
    
The parameterless ctor can actually be thought of as a kind of IoC container w/out an IoC container @Mat'sMug. –  RubberDuck 12 hours ago
    
@RubberDuck, that's some hardcore stuff –  Nikita Brizhak 3 hours ago
1  
@NikitaBrizhak it's actually a trick I learned from Michael Feather's book "Working Effectively with Legacy Code". Good read. I highly recommend it. –  RubberDuck 2 hours ago