Constructor Injection

Constructor injection is useful to make your class dependencies explicit in the constructor of your class. This is done by having a parameter in the constructor for each dependency.
As a class might have multiple constructors, you need to specify which constructor the container should use to determine the dependencies of your class. The Constructor attribute is used to mark the constructor method chosen, as shown in the following code fragment:
public class WithClassDependency
{
    [Constructor]
    public WithClassDependency(WithoutDependencies dep)
    {
        ...
    }
}
Important: When no constructor is marked with the Constructor attribute, Needle defaults to the parameterless constructor. If the class does not have a parameterless constructor, an exception is thrown.

Named Dependencies

There might be some scenarios in which a constructor dependency has been registered with an Id in the container. To get Needle to inject the correct instance based on that Id, the Dependency attribute must be used. The Dependency attribute must decorate the constructor's parameter in which a specific registration Id is required, as shown in the following code:
internal class MockWithNamedDependency
{
    [Constructor]
    public MockWithNamedDependency([Dependency("Mock")] MockDependency dependency)
    {
	...
    }
}

Related Topics

Last edited Jan 21, 2011 at 2:00 AM by dschenkelman, version 3

Comments

No comments yet.