views:

94

answers:

3

i'm trying to find an example in .NET of a class that uses Dependancy Injection (e.g. a class that uses a Builder or Factory in order to create the full object - injecting dependencies as it does)

Browsing through Reflector, i would have thought some of the more complicated ado.net or WebRequest objects would use dependency injection - but no.

Can anyone point to an example inside the .NET framework of an object that uses dependency injection to get its work done?

+1  A: 

I think there's DI littered all over the .NET Framework, but it's a special form of DI called "Property Injection" -- in the Java world it's frequently called "Setter Injection".

Randolpho
Can you point me to one of them?
Ian Boyd
+2  A: 

Here are a couple of examples of dependency injection in the framework:

WCF's ChannelDispatcher has constructor injection (mandatory dependency) of IChannelListener. In general though, WCF relies on configuration to do user-level injection of optional dependencies.

System.Xml does poor-man's dependency injection in a number of places. For example, XmlDocument has a constructor injection (internal) on XmlImplementation. The default constructor just instantiates the needed XmlImplementation. XmlImplementation itself depends on XmlNameTable. XmlResolvers are another example of injection.

MEF's CompositionContainer optionally depends on a ComposablePartCatalog and ExportProviders. ImportEngine has constructor injection of ExportProvider

ASP.NET MVC's Controller has setter injection on IActionInvoker and ITempDataProvider (they have default implementations) Model binders are also injectable.

If you're just starting out with dependency injection, IMHO the .NET framework is the worst place you can learn from: most of the time you won't have the source code, it's framework-level (not application-level) code with quite special requirements. In particular Microsoft is very careful to make things public (default is internal), as opposed to most open source projects, in order to better manage their breaking changes.

Mauricio Scheffer
A: 

Here's a real simple (silly) example of Dependency Injection via a Factory:

public class MyService1Factory {
    public IMyService1 Create() {
        MyService2 service = new MyService2();
        // provides dependent IMyService2 for MyService
        return new MyService(service);
    }
}

public class MyService : IMyService1 {
    private IMyService2 service;

    // MyService depends upon IMyService2, an instance of this "dependency" is 
    // passed in (or "injected") via a simple constructor param
    public MyService(IMyService2 myService2) {
        service = myService2;
    }
}
Max
But the OP was asking for DI examples in **framework** code.
Mauricio Scheffer