For my ASP.NET MVC projects, I used to rely heavily on static methods for my data access, kind of like this :
public class MyTable
{
public static IEnumerable<MyTable> findAll()
{
using (var connection = new SqlConnection(Provider.connString))
{
//implementation here
}
return datas;
}
public static MyTable find(guid id)
{
using (var connection = new SqlConnection(Provider.connString))
{
//implementation here
}
}
}
so i could call them like this in my controller :
var datas = MyTable.findAll();
I'm comfortable with it, but I doubt I'm doing a good practice for data access with it.
now, I'm trying to apply dependency injection just for some learning purpose to my data access class something like this :
public class MyTable
{
public IDatabaseEngine _engine = null;
public MyTable()
{
}
public MyTable(IDatabaseEngine engine)
{
_engine = engine;
}
public IEnumerable<MyTable> findAll()
{
using (var connection = _engine.getConnection())
{
//implementation here
}
return datas;
}
public MyTable find(guid id)
{
using (var connection = _engine.getConnection())
{
//implementation here
}
return data;
}
}
the thing is, it means that I have to create an instance of MyTable
class to invoke method for data access on my controller something like this :
var table = new MyTable(new MSSQLEngine(provider.connString));
var datas = table.findAll();
well either I'm very inexperienced to figure this out or I'm doing it wrong, I feel uncomfortable doing instantiation of object for every data access I need.
My question is
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With