Search code examples
c#unity-container

How to resolve unity dependency in console app from constructor of new instance


Background:

I used Unity IoC only in WPF Application until now.
I would like to use is in a console application.
In the WPF Application runs some "magic" to automatically choose the correct constructor of the new object/instance.

Question:

How I use the same "magic" in my console application?

static void Main(string[] args)
{
    IUnityContainer unitycontainer = new UnityContainer();

    // RegisterType of Dependency in container
    unitycontainer.RegisterType<IMyDependency,Dependency>(new ContainerControlledLifetimeManager());

    // How shall I choose the correct constructor?
    // In WPF Application the correct constructor was used automatically
    // How the wpf apps use the correct constructor with my dependencies?
    var newclass = new newclass();
}

public class NewClass
{
     private readonly IMyDependency _dependency;

     public NewClass(IMyDependency dependency)
     {
         _dependency = dependency;
     }
}

Solution

  • Call IUnityContainer.Resolve to instantiate the class which will call the constructor with the registered dependencies.

    var newclass = unitycontainer.Resolve<NewClass>();