adaoss
adaoss

Reputation: 15

c# Convert variable value to object

I need a way to convert the value of a variable into an object.

Lets assume a variable

string viewName = "taDataView";

I need a way to convert the value of variable into something like this:

taDataView viewModel = Container.Resolve<taDataView>();

Something like eval() in php...

Thanks for your help.

Upvotes: 0

Views: 710

Answers (1)

TrueWill
TrueWill

Reputation: 25523

One option is to use Unity's Named Registrations (see Resolving an Object by Type and Registration Name in the Unity 2.0 help file). You would still need to know the base type (generally an interface).

// Create container and register types
var myContainer = new UnityContainer();
myContainer.RegisterType<IMyService, DataService>("Data");
myContainer.RegisterType<IMyService, LoggingService>("Logging");

// Retrieve an instance of each type
var myDataService = myContainer.Resolve<IMyService>("Data");
var myLoggingService = myContainer.Resolve<IMyService>("Logging");

Alternatively, see Create an object knowing only the class name (especially Marc Gravell's answer).

EDIT: Revised the example to use generics.

Upvotes: 1

Related Questions