There are three Object Oriented relationship types i.e. Aggregation, Composition and association as described here: What is the difference between association, aggregation and composition?.
IOCs support composition by allowing you to do this:
public class MyClass
{
MyClass2 MyClass2;
public MyClass(MyClass2 myClass2)
{
MyClass2 = myClass2;
}
}
I believe the code above is an example of Aggregation as MyClass is not responsible for the lifecycle of MyClass2.
Here is an example of Association i.e. MyClass2 is passed to the method (instead of being injected into the class):
public void MyMethod(MyClass2 myClass2)
{
//Do something
}
I can do something like this for Composition:
public class MyClass
{
WindsorContainer Container;
MyClass2 MyClass2;
public MyClass(WindsorContainer container)
{
Container=container;
MyClass2 = Container.Resolve<MyClass2>();
}
}
However, I believe the Composition example uses the Service Locator anti pattern. How do I use composition without using the Service Locator pattern?
If you find yourself using the Service Locator Pattern you are correct to question it, but it has it's place and is OK to use if you need to.
One thing that you may be slightly off on is how IoC injects. IoC can do constructor, property and method injection, so your association example can still be dependency injection.
Composition without IoC is fine if the object doesn't provide any real logic. If what you want to compose into your class is just a DTO, then you don't need to inject it anyway.