I've been thinking a bit on how dependency injection could be better integrated directly into a C# like language. I've come up with a potential solution I'd like to hear your opinion on. I haven't used many dependency injection frameworks so there might be something I'm overlooking
Anyways, the idea is to be able to declare properties as "injectable" using a keyword. When an object is instantiated, and that property is not initialized through the constructor, or object initializer, it requests an instance of that property type from some global service.
Similarly you register handlers for different types to that service so that you can instantiate the injected property type.
The upside of using this kind of architecture IMO is that it's fairly flexible and easy to use. The downside is that there might be some overhead of doing the callout to the singleton each time you initiate a class that has injection.
Then again that's only an issue for classes that get's instantiated frequently in a high performance solution so it shouldn't be much of an issue. Perhaps you could use some kind of factory in those instances.
Thought, issues, questions, better ideas?
Code
public class SomeClass
{
public SomeClass()
{
//implicit behavior if Animal is not set in constructor or initializer
this.Animal = GlobalInjector.Get(this,typeof(Mammal))
}
public injectable Mammal Animal
{
get;
set;
}
}
GlobalInjector.Register(typeof(Mammal), () => return new Mammal(someParameter));