Dependency Injection Challenges With .Net

Dependency injection is the process of injecting dependent objects into an object. A class should not be responsible for creating objects it depends on. Those objects should be injected with Dependency injection. This indirection makes classes and large systems more loosely coupled improving maintainability.  .Net has numerous Dependency Injection frameworks to choose from such as Structuremap, Ninject, Autofac, Unity, Castle Windsor and Sprint.Net to name a few. I won’t compare each of the frameworks here, but rather I’ll focus on how to structure classes and assemblies. This structure can be applied to any of the frameworks.

Inversion of Control is the primary use of Dependency Injection. In traditional applications, higher level modules depend on lower level modules. This has the unfortunate side effect that lower level changes can have a ripple effect on higher level modules.  Higher level modules usually have the more complicated logic and meat of the application and should be insulated as best as possible from changes in other modules.

When classes are within an assembly, applying dependency injection involves introducing an interface to invert the dependency. As you can see below, the Logic class no longer depends on the DataAccess. The DataAccess now depends on the Logic Interface.

When Structuring projects within visual studio, top-most level projects, whether they are a User Interface or application will ultimately need to reference all assemblies since they need to know what assemblies need to be loaded. Below is how I structure projects.

Dependency Diagram

Project Structure

I have left out how the actual wiring of dependencies works. To wire up each project I contain the Dependency Injection logic in a single class per assembly. At some point you may want to replace the Dependency Injection framework so it’s best to minimize dependencies on it throughout a project.

This entry was posted in .Net and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s