简体   繁体   中英

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;
     }
}

调用IUnityContainer.Resolve实例化该类,该类将使用已注册的依赖项调用构造函数。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM