views:

679

answers:

4

I am just getting started using any DI/IoC toolset and have a very basic question. I am using Unity as we will also be using a number of the Enterprise Library blocks throughout the application.

The question that I have is around the dependencies to .NET framework classes. For instance, in one of the classes that I am working on currently, I need to create DirectoryInfo classes. According to my understanding, one of the best practices in DI is to never use the "new" keyword - as this introduces a hard dependency. So how should I get a new DirectoryInfo? Add it as an item to the container and have the container a dependency of the class? This seems that it would be impratical in real life usage as I would end up with the container being configurated with literally hudreds to thousands of framework classes. I would consider that to be a maintance nightmare.

A: 

I would say that is a little over engineering. I would think that the path of the DirectoryInfo to create should be passed in or have some sort of configuration repository( or service) class passed in that holds (or gives you a way to get) that data.

CSharpAtl
A: 

I wouldn't register low-level classes like DirectoryInfo with the container - it's not really a problem to use new in some places in your application, as long as this requirement doesn't 'leak out' into higher-level classes. So in this example, it probably makes sense to create and use the DirectoryInfo directly in a class, yet have instances of that class be injected into their dependents by the container.

Lee
A: 

First you can look as SystemWrapper library. It wraps DirectoryInfo object so you can mock it.

Next you can look at tutorial to TDD using Rhino Mocks and SystemWrapper. You can see there usage of DI; however, the example there doesn't use any of IoC.

Hope it helps.

Vadim
A: 

The way I see it, the majority of classes in the BCL (base class library) are utiity classes, and generally don't have a ton of other dependancies other than straight up call graphs.

DI is designed to flatten the call graphs and prevent a lot of cross talk between classes. As such, and the fact that you can't do anything about the BCL chattiness, you might as well just accept them for what they are and go ahead and use new...

The only reason why you wouldn't want to, is for testing purposes. You're not typically testing BCL classes, but you might want to replace a BCL class with a mocked version so that it doesn't actually do whatever it is the class does, only pretend to do so.. and you can use stuff like SystemWrapper to do that if necessary.

Mystere Man