Unity supports auto-wiring which allows you to resolve complex object graphs and not just individual objects.
For example, let´s say that you have a class Car implementing ICar that depends on another class IEngine using constructor injection (Car´s constructor requires a parameter of type IEngine).
public interface ICar
{
void Accelerate();
}
public interface IEngine
{
void Accelerate();
}
public class Car: ICar
{
private readonly IEngine _engine;
public Car(IEngine engine)
{
_engine = engine;
}
public void Accelerate()
{
_engine.Accelerate();
}
}
public class Engine: IEngine
{
public Engine()
{
}
public string Message {get; set;}
public void Accelerate()
{
Console.WriteLine("Accelerating." + Message);
}
}
You will then register in Unity how to resolve ICar and IEngine:
var _container = new UnityContainer()
.RegisterType<ICar,Car>()
.RegisterType<IEngine,Engine>(
new InjectionProperty("Message", "Hello world"));
Then when you resolve ICar Unity will be able to provide an instance of Engine to the Car constructor, auto-wiring the dependency that Car has on IEngine. This is also true for any additional dependencies that Car or Engine may have and any properties registered for injection.
var car = _container.Resolve<Car>();
car.Accelerate();
Accelerating.Hello world
This way by resolving an ICar Unity will give you the full object graph needed. You can try the sample in this fiddle
EDIT
You can register a type to be resolved using a lambda method that will be executed at runtime, for example:
public interface IFoo
{
DateTime ResolvedTime {get; set;}
}
public class Foo: IFoo
{
public DateTime ResolvedTime {get; set;}
}
//Can be registered using a lambda as in:
container.RegisterType<IFoo,Foo>(
new InjectionFactory(c => new Foo{ ResolvedTime = DateTime.Now }));
You can get some info on the msdn. I have also updated the fiddle above with this lambda example.