If you're looking for a solution that works for most applications you can register the component at the highest level, and then resolve it. As long as you resolve the instance Unity will resolve the dependencies (such as IUnityContainer).
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Registering dependencies ...");
var container = new UnityContainer();
container.RegisterType<ProgramStarter, ProgramStarter>();
// Do other registrations.
var program = container.Resolve<ProgramStarter>();
// Since ProgramStarter was resolved using Unity it will also resolve the container.
program.Run();
}
}
public class ProgramStarter
{
public ProgramStarter(IUnityContainer container)
{
// Do something with container.
}
public Run()
{
// Do stuff.
}
}
Or an example for WPF:
IUnityContainer container = new UnityContainer();
// Do registrations.
var window = container.Resolve<MainWindow>();
window.Show();
MainWindow
will now be able to resolve both the container and other dependencies.
Also, have a look at this question: Where to place and configure IoC container in a WPF application?
As a sidenote I usually keep my container as a static instance, and seen a lot of other implementations doing the same thing. I find it convenient to be able to use it when you find yourself in a situation when it's not possible to resolve it.
public static class IocContainer
{
private static readonly Lazy<IUnityContainer> Container = new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
// Possibly do registrations here as well...
return container;
});
public static IUnityContainer Instance
{
get { return Container.Value; }
}
}