Domanda

I'm (somewhat) new to DI and am trying to understand how/why it's used in the codebase I am maintaining. I have found a series of classes that map data from stored procedure calls to domain objects. For example:

Public Sub New(domainFactory As IDomainFactory)
  _domainFactory = domainFactory
End Sub

Protected Overrides Function MapFromRow(row As DataRow) As ISomeDomainObject
  Dim domainObject = _domainFactory.CreateSomeDomainObject()
  ' Populate the object
  domainObject.ID = CType(row("id"), Integer)
  domainObject.StartDate = CType(row("date"), Date)
  domainObject.Active = CType(row("enabled"), Boolean)

  Return domainObject
End Function

The IDomainFactory is injected with Spring.Net. It's implementation simply has a series of methods that return new instances of the various domain objects. eg:

Public Function CreateSomeDomainObject() As ISomeDomainObject 
  Return New SomeDomainObject()
End Function

All of the above code strikes me as worse than useless. It's hard to follow and does nothing of value. Additionally, as far as I can tell it's a misuse of DI as it's not really intended for local variables. Furthermore, we don't need more than one implementation of the domain objects, we don't do any unit testing and if we did we still wouldn't mock the domain objects. As you can see from the above code, any changes to the domain object would be the result of changes to the SP, which would mean the MapFromRow method would have to be edited anyway.

That said, should I rip this nonsense out or is it doing something amazingly awesome and I'm missing it?

È stato utile?

Soluzione

The idea behind dependency injection is to make a class (or another piece of code) independent on a specific implementation of an interface. The class outlined above does not know which class implements IDomainFactory. A concrete implementation is injected through its constructor and later used by the method MapFromRow. The domain factory returns an implementation of ISomeDomainObject which is also unknown.

This allows you supplement another implementation of these interfaces without having to change the class shown above. This is very practical for unit tests. Let's assume that you have an interface IDatabase that defines a method GetCustomerByID. It is difficult to test code that uses this method, since it depends on specific customer records in the database. Now you can inject a dummy database class that returns customers generated by code that does not access a physical database. Such a dummy class is often called a mock object.

See Dependency injection on Wikipedia.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top