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
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).
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With