Assuming Worker
is registered in the container, either as a concrete type or IWorker
:
var worker = _container.Resolve<IWorker>();
or
var worker = _container.Resolve<Worker>();
and then:
worker.Start();
That should be all you need if Worker is at the top of your object graph, and all dependencies flow from it. This is not service location, as you are only calling Resolve() once, and doing so in your composition root. Only the composition root knows about your container.
Edit
From your comments--so assuming this is your setup:
public class Root
{
private readonly A _a;
public Root(A a)
{
if (a == null) throw new ArgumentNullException("a");
_a = a;
}
}
public class A
{
private readonly B _b;
public A(B b)
{
if (b == null) throw new ArgumentNullException("b");
_b = b;
}
}
public class B
{
private readonly C _c;
public B(C c)
{
if (c == null) throw new ArgumentNullException("c");
_c = c;
}
}
public class C
{
}
Assuming you had all the registrations set up correctly in Unity, you would just Resolve at the top of the graph:
var root = _container.Resolve<Root>();
The container would do the rest. "root" is now a container-managed object, and because of this the container can resolve the full graph of dependencies.
This is constructor injection, not service location. The only object in the system that knows anything about the container is the composition root--the only place you call Resolve() is in the Main() method.
Again, I may be misunderstanding something about your question, but what I am describing is pretty much the basic use case of DI + constructor injection.