seanicus
seanicus

Reputation: 1171

Am I properly representing dependency injection in UML?

So, I am trying to get started with UML class diagrams and as a sort of exercise I am trying to model some existing code. Lets say I have this:

public interface IDataContextWrapper : IDisposable
{
     //blah blah blah
}

public class DataContextWrapper<T> : IDataContextWrapper where T : DataContext, new()
{
     //blah blah blah
}

public class ArtistRepository
{
     L2SDCWrapper.Interfaces.IDataContextWrapper dataContext;

     public ArtistRepository()
         : this(new DataContextWrapper<ChinookDataContext>())
     {
     }

     public ArtistRepository(IDataContextWrapper dc)
     {
         dataContext = dc;
     }

     //blah blah blah
}

I've come up with this:

done using visual studio modeling tools

My concerns:

Upvotes: 4

Views: 6713

Answers (1)

Uffe
Uffe

Reputation: 10504

It is generally not a good idea to try to represent every detail of an implementation in UML. UML is better for describing design, and there is to my knowledge no standardized UML profile (= adaptation) for C#, or indeed most other languages.

That said, here's a couple of pointers:

  1. Dependencies are rather weak, unspecific connections. The two Interfaces should be connected by a Generalization (inheritance).
  2. UML allows for representation of generics / templates / parameterized classes. The specifics of modelling such classes depend on the tool you're using.
  3. The parameterless ArtistRepository constructor actually creates an object of an anonymous class. You can represent that class in the class diagram if you wish, but if you really want to get into that level of detail it is probably better to draw a sequence diagram for the constructor.

Here's a class diagram along those lines, drawn in Sparx Systems' Enterprise Architect: enter image description here

Note the parameterized DataContextWrapper and the abstract DataContext. It wasn't included in the code sample but I assumed it's an abstract class; if it is in fact an interface the relationship should be a Realization rather than a Generalization.

I've modelled two versions of ArtistRepository, one using an attribute and one using a directed association to represent the dc member. These two are semantically equivalent in UML.

I've only drawn the dependencies to DataContextWrapper and ChinookDataContext from one of them, but that's just so this example doesn't get too cluttered; whichever representation you choose should have both relationships of course.

I have not modelled the anonymous class created by the ArtistRepository constructor. For an overview I think this is plenty.

Upvotes: 4

Related Questions