Question

I'm sure this is not a big deal and the application is not big but I'm trying to practice DI anywhere I can, for experience. I have the following class and all it does is parse some arguments entered by a user in a console application and return an instance of ICommand based on the arguments passed in. The design using commands in console apps is taken from Mark Seeman's book Dependency Injection in .NET. My problem is one implementation of the ICommand class needs an instance of IDocumentService. Right now to make sure I can satisfy the dependency to my ICommand I'm passing the IDocumentService into the Parser using constructor injection. This seems odd to me because I think that if a class has a dependency it should use that dependency, not just pass it on to a dependency. At the same time I think it would be overkill if I built an abstract IDocumentServiceFactory so that the Parser class could resolve the IDocumentService later than the document root. Any guidance to resolve this design issue is appreciated.

public class GasTranParser
{
    private readonly IArchiveService service;
    public GasTranParser(IArchiveService service)
    {
        if(service == null)
            throw new ArgumentNullException("service");
    }


    ICommand Parse(IEnumerable<string> args)
    {
        if (args == null || args.Count() != 1)
            return new HelpCmd();

        List<string> argsList = args.ToList();

        return new GasTranComposerCmd(service, argsList[0]);
    }
}
Was it helpful?

Solution

I don't see any problem with passing dependencies in general, but in your particular example, it seems like you would want to pass a ICommandFactory to your GasTranParser instead, and let the concrete CommandFactory create the GasTranComposerCmd instances with the proper service:

public class GasTranParser
{
    private readonly ICommandFactory command_factory;

    public GasTranParser(ICommandFactory command_factory) { ... }    

    ICommand Parse(IEnumerable<string> args)
    {
        if (args == null || args.Count() != 1)
            return new HelpCmd();

        List<string> argsList = args.ToList();

        return command_factory(argList[0]);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top