C # mvc dynamically creates a controller from a string name - eval?

I would like to create a new instance of the controller through the string name. In classic ASP, I would do eval, but how to do it in C #?

eg:

If I wanted to create an instance of "AccountController", I would usually write:

var Acc = new AccountController();

Now, if the controller name is only available as a string, how can I instantiate an object?

eg,

var controllerName = "AccountController";

var acc = new eval(controllerName)();

Thanks for the help!

Franc

+3
source share
3 answers

If your controller is inside the assembly, you just need the class name, otherwise you need the full name (namespace and assembly). You would do it using reflection. Sort of:

Type t = Type.GetType("NameOfController");
var  c = Activator.CreateInstance(t);

, (System.Reflection).

+7

IOC . , . , .

, IOC , .

AutoFac

var b = new ContainerBuilder();
b.Register<AccountController>().As<IController>().Named("AccountController");
var c = b.Build();

var controller = c.Resolve<IController>("AccountController");
+5

Activator.CreateInstance, , ( ). , . , , . MVC - , . MVC ( , ) .

+2

Source: https://habr.com/ru/post/1723776/


All Articles