Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# mvc dynamically create controller from string name - eval?

Tags:

c#

asp.net-mvc

I'd like to create a new instance of a controller, via a string name. In classic ASP I'd do an eval, but how to do it in c#?

eg:

If I wanted to create an instance of the "AccountController, normally I'd write:

var Acc = new AccountController();

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

eg,

var controllerName = "AccountController";

var acc = new eval(controllerName)();

Thank you for any help!

Frank

like image 627
frank Avatar asked Jan 27 '26 21:01

frank


2 Answers

If your controller is within the assembly you just need a class name, otherwise you need a fully qualified name (namespace and assembly). You would do it using reflection. Something like:

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

There are other ways, but all involve reflection (System.Reflection).

like image 138
epitka Avatar answered Jan 29 '26 11:01

epitka


An IOC container would allow this functionality. When you register your controller type, just provide a name. Then you can return a fully instantiated object from the controller by providing the name.

Also, most IOC containers will allow you to automatically register types base on an interface or base class, so you wouldn't even need to register all of your controllers manually.

An example in AutoFac

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

var controller = c.Resolve<IController>("AccountController");
like image 23
Jason Avatar answered Jan 29 '26 11:01

Jason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!