I have a code similar to this:
public static IEnumerable<T> ParseInput<T>(string input)
{
var xml = XElement.Parse(input);
// some more code here
var parser = Container.Current.Resolve<IParser<T>>();
return parser.Parse(xml);
}
It contains some common processing of the data followed by a call to parser interface which is very different between the specializations. Currently, I am resolving the parser interface from a container – but I’m a bit uncomfortable with using a container from a static method.
Is there a better or alternative way to resolve the interface, besides this and the switch statement?
Edit: In my opinion, the shagginess of this comes from an attempt to marry unit-testable OO programming (IoC, no static classes) to functional programming. Where is the cleanest line of separation? Probably resolving the parser earlier and passing it into the static method.
Edit: I kinda missed what you meant. I quite like using a container for things like that. Switch statements are a bit ugly. So going with a container, some ways you could make it more testable are:
If
some code hereis complicated, I tend to make sure it is not static, as its not as easy to unit test static methods when using dependency injection. If its not complicated, your code is fine to me :o)Option 1: Don’t use a static method.
Instead use an instance method and inject the parser into it.
Option 2: Pass in the container resolver along with the string input. Although if doing this, option 3 is better.
Option 3: Pass in the already resolved parser (credit to Mark Seemann for this idea)