从单独的类库访问 web.config? [英] Access web.config from separate Class Library?

查看:21
本文介绍了从单独的类库访问 web.config?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种实现以下目标的好方法:

I'm looking for a good way to achieve the following:

我有一个 Web 应用程序 (MVC 3),它有一个单独的类库,其中包含我正在制作的 CMS 的后端逻辑.这个 CMS 使用 NHibernate 连接到数据库.我希望用户能够在他们的 web.config 文件中配置连接字符串(甚至是数据库的风格).

I have a web application (MVC 3), with a separate Class Library that contains the back-end logic of a CMS that I'm making. This CMS uses NHibernate to connect to a database. I want the user to be able to configure the connectionstring (and eventually even the flavour of the database) in their web.config file.

我正在寻找一种从 web.config 文件中获取连接字符串的好方法,即使 DLL 是完全独立的.这可能吗?我是否必须以某种方式将我的连接字符串传递给我的类库?或者我可以在应用程序运行时访问它吗?

What I'm looking for is a good way to get the connection string from the web.config file, even though the DLL is completely separate. Is this possible? Will I have to pass my connection string to my class library somehow? Or will I be able to access it when the application runs?

如果我必须在我的 web 应用程序中创建一些代码来将连接字符串传递给我的类库,我怎样才能使这段代码尽可能可移植,这样我就不必为我的下一个 web 应用程序再次编写它?

If I have to create some code in my web application to pass the connection string to my Class Library, how can I make this code as portable as possible, so I won't have to write it again for my next webapp?

非常感谢您的任何想法.

Thanks a lot for any ideas you have.

推荐答案

您可以从网站将连接字符串传递给类库中的类.

You can pass in the connection string to the classes in the class library from the web site.

与尝试直接从配置文件中获取信息相比,这是一个更好的选择,否则您将依赖于存在正确键的配置文件(使测试类变得有些困难).

This is a better choice than trying to get the information directly from the configuration file, as otherwise you will have a dependency on the configuration file existing with the exact right key (making testing the class somewhat harder).

参见这篇博文 反对直接访问配置的论据(这是很常见的做法,但不是最佳实践).

See this blog post for arguments against accessing configuration directly (which is very commonly done, but is not best practice).

这篇关于从单独的类库访问 web.config?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆