开发者

Can I make an object type configurable?

In code, I have a variable defined like

A a = new A();

开发者_StackOverflow社区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#?


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.


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


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.


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.


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜