Search code examples
c#.netdependency-injectionfactory-pattern

Getting an instance of a class that uses dependency injection


I've been reading about dependency injection, and I'm getting the basics. Most of the examples on the internet explain it till here:

public class MyClass
{
    private IDependency _dependency;

    public MyClass(IDependency dependency)
    {
        _dependency = dependency;
    }
}

This way, we inject the dependency through the constructor. But I don't think it's a good idea to keep writing:

var myClassInstance = new MyClass(someArgument);

all throughout the code. Should I use the factory pattern to get instances?

public static class MyClassFactory
{
    private static IDependency dependency = DependencyFactory.GetInstance();

    public static MyClass GetInstance()
    {
        return new MyClass(dependency);
    }
}

Is this the way to go?

I know that using a DI container solves the problem, but I'd like to learn how to incorporate dependency injection in my code, before using a DI container.


Solution

  • Yes, a factory would be the way to go. In fact, a DI container is really just a glorified factory that can be configured via xml (in the case of spring for example) or code (for something like structure map)