Skip to content

Instantly share code, notes, and snippets.

@jhoerr
Created October 14, 2013 15:52
Show Gist options
  • Save jhoerr/6977840 to your computer and use it in GitHub Desktop.
Save jhoerr/6977840 to your computer and use it in GitHub Desktop.
Three examples of how to get a dependency, FooProvider, into a class that needs it.
// Bad!
// The FooProvider is instantiated in the constructor. Very hard to test.
public class OldSchool
{
private FooProvider _fooProvider;
public OldSchool()
{
_fooProvider = new FooProvider();
}
}
// Better!
// A concrete instance of FooProvider is given by TheAppServiceLocator,
// but we still have to know to set up the TheAppServiceLocator beforehand.
public class SerivceLocator
{
private IFooProvider _fooProvider;
public SerivceLocator()
{
_fooProvider = TheAppServiceLocator.Get<IFooProvider>();
}
}
// Best!
// An instance of FooProvider is injected into the constructor.
// All dependencies are resolved in the ctor(), and IFooProvider can be easily mocked for testing.
public class DependencyInjection
{
private IFooProvider _fooProvider;
public DependencyInjection(IFooProvider fooProvider)
{
_fooProvider = fooProvider;
}
}
public interface IFooProvider
{
}
public class FooProvider : IFooProvider
{
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment