user496949
user496949

Reputation: 86075

Can I make an object type configurable?

In code, I have a variable defined like

A a = new A();

I would like to make A be configured in the app.config, so I can change to to B just by modifying the app.config. I am wondering if I can do this using C#?

Upvotes: 2

Views: 198

Answers (5)

dexter
dexter

Reputation: 7203

As everybody said, an IoC container is the perfect way to go. Or you can use the brute force way:

    Assembly assembly = Assembly.Load(...);
    var obj = assembly.CreateInstance(ConfigurationManager.AppSettings["MyDynamicType"], true);

    return obj as IDynamicObject;

Upvotes: 0

Chance
Chance

Reputation: 11285

You would do this a bit differently but using what is known as dependency injection via an IoC (inversion of control) container.

My favorite is ninject but you should easily be able to find a list of them here somewhere.

Edit I forgot to mention Clay. It can do some pretty rad stuff via the new dynamic addition to .net 4.0.

Upvotes: 3

gstercken
gstercken

Reputation: 3271

You mean you want to instantiate a type based on its type name as a string? Have a look at Activator.CreateInstance().

Upvotes: 1

Mike
Mike

Reputation: 5998

Sounds like to me you're going about this the wrong way.

From what you've posted, I suspect you want to be able to use mostly simmilar - yet different - classes at runtime (dependant on a configuration or runtime logic of some sort).

For this I would strongly suggest a redesign/rethink of your problem. It sounds perfect use case for the design pattern of Abstract Factory. (With a combination of some decision logic on how you see fit to decide which concrete-class you wish to instantiate.

Upvotes: 0

Paul Sasik
Paul Sasik

Reputation: 81429

Take a look at Castle Windsor, a mature, open source project that nicely meets your requirement. And if you don't want to use the library directly you could browse the source code for ideas on implementation.

Upvotes: 0

Related Questions