While re-factoring a project with the objective of not making it dependent on a concrete type but an abstraction of it I've been faced to the issue that I would need to add a reference to a project which I didn't want to.
So I've sketched the following piece of code which works pretty well :
Usage :
// Old line of code that directly referenced AudioStream
// AudioStream = new AudioStream(value);
// New code that tries to find a concrete implementation of IAudioStream
var type = typeof(IAudioStream);
var implementation = TryFindImplementation<IAudioStream>();
if (implementation == null)
throw new InvalidOperationException(
"Could not find an implementation of " + type.Name);
var instance = Activator.CreateInstance(implementation, value);
AudioStream = (IAudioStream)instance;
Method that tries to find a concrete implementation:
private static Type TryFindImplementation<T>()
{
return (
from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
where typeof(T).IsAssignableFrom(type)
where type != typeof(T)
select type)
.FirstOrDefault();
}
Can this piece of code considered as a very simple form of Dependency Injection ?