static methods vs dependency injection for data access layer

While DI is cool for some cases but in most cases is an over engineering!.

I explain. How to creates a static method. Just put "static" in front of the method. And you could call it easily by calling the Class.Method(). Also, its efficient to the system, because the method is only created once.

Pro: is efficient. Cons: is not mutable

While DI, you may be need some container, then an interface, and you could add a class, any class that implements the interface. And, in some part of the code, you will need to create an instance of the class (ergo a new instance of the method).

Pro: is mutable Cons: is not efficient, its verbose.


Answers to your questions:

  1. No, see below detailed answer
  2. Main advantage of DI is dependency on abstraction not on implementation. You don't need to create instances of classes, DI will do it for your. You just need to inject interfaces into your classes and register them in your IoC.
  3. No, as you will no be able to write unit tests to your methods.
  4. See below.

To use correctly DI, first you need extract MyTable class into an interface and then inject that interface into your controller.

public interface IMyTable 
{
    IEnumerable<MyTable> findAll();
    // other methods
}

public class MyTable : IMyTable 
{
    // your implementation
}

Then your controller should look like:

public class YourController : Controller
{ 
    private IMyTable myTable;
    public YourController(IMyTable myTable)
    {
        this.myTable = myTable;
    }

    public ActionResult YourAction()
    {
        var result = myTable.findAll();
        // ...
    }
}

I personally use Castle Windsor as IoC container, here is an example of using Castle Windsor in ASP.NET MVC application