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?