简体   繁体   中英

Unity run-time resolving?

I have the following code in a console program.

interface I { ...; string X { get; }; string Y {get; }; string Z {get; } ...}
class A : I {...}
class B : I {...}
class C : I {...}

The program accept command line parameters like test.exe b -x 10 -z 20 . And it will create an instant of B and set X to 10, Z to 20.

How to implement this using unity? This may be a newbie question.

You need to register named mapping against same interface and resolve using the name passed as argument.

var container = new UnityContainer();
container.RegisterType<I, A>("a");
container.RegisterType<I, B>("b");
container.RegisterType<I, C>("c");

I instance = container.Resolve<I>(args[0]);

Read Registering Type Mappings with the Container for explanation

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