-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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