开发者

Can I add web/app config values to a project automatically when my dll is referenced?

If a had a dll that depends on the existence of a small set of app setting keys, or maybe a small custom xml section at runtime, is there an event I can respond to in my assembly when the reference occurs that I can use to write to the project's confi开发者_StackOverflow社区g file to insure the default values exist?


While the specific thing you're asking for (implementing custom OnReferenced logic in an assembly) is not possible, the use case you're describing (some libraries simply do require the host app to provide some config settings) is very common. Fortunately, there is NuGet, a brilliant .Net package manager, which provides a very neat way of achieving exactly that.

All it requires you to do is to create a package that contains your assembly, and then to use the NuGet Visual Studio extensions to reference that package.

See here for an introduction on how to create packages. This link will show you precisely how to add config file transformations to a NuGet package.

NuGet is also widely covered here on StackOverflow, so that you should easily find everything to get started.


No you can't, and there is a reason for this.

I would be terrified if a library could changes to my application configuration file. What if I'm generating it on the fly? What if another utility downloads it from the net? What if I'm using app.config tranformations? What if your code is plain wrong and you mess up my existing settings?

What if, after all, I don't want my application to have a configuration file? If my application is a SharePoint webpart or some website plugin and there's no access to (production) web.config from development environment?

If you think your library really needs XML configuration, keep it in a configSections but it's really up to the calling application to supply these settings. Create a settings class that library callers may use as an alternative to specifying XML configuration and assume default values in it. Introduce some kind of static property to hold these settings.

Take NLog as a good example. It allows to specify settings both using code API and XML configuration which can just as well reside in application configuration section, a separate file in the same directory or in the library directory. This may be an overkill for your purposes; I'm just saying that you should consider all use cases before sticking to a particular configuration solution.


The dot net frame work does not provide methods to write back to the config file .. however it is just a XML file, which dot contains many functions for, doing a quick search came up with Writing to Your .NET Application's Config File

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜