tags:

views:

190

answers:

3

Hi,

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

+4  A: 

If controller is within assembly you just need a class name, otherwise you need 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) .

epitka
+1  A: 

You can use Activator.CreateInstance but you need to know both the name of the type and of the assembly containing it (or meet other conditions). That shouldn't be too hard since all of the controllers are in a single assembly. I'd really like to know why you think you need to do this, though. I've done a couple of fairly large projects in MVC and can't think of any reason outside of unit testing where I needed to create a controller at all. The MVC pattern provides good separation of concerns and creating a controller (from a string, no less) smells like a pattern violation.

tvanfosson
+3  A: 

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");
Jason