如何在servicestack中配置mongodb

时间:2013-09-26 21:51:57

标签: asp.net mongodb servicestack

我正在尝试使用MongoDB作为ServiceStack的身份验证模块的持久性后端,因此我在web.config中添加了以下节点:

<connectionStrings>
    <add name="myDb" connectionString="mongodb://localhost/mydb?safe=true" />
</connectionStrings>

以下是我的Configure方法:

public class MyAppHost : AppHostBase
{
    public MyAppHost () : base("My Web Services", typeof(MyService).Assembly)
    {
    }

    public override void Configure(Container container)
    {
        Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] {
            new BasicAuthProvider()
        }));
        Plugins.Add(new RegistrationFeature());

        var connectionString = ... // how do I retrieve "mongodb://localhost"?
        var dbName = ...           // how do I retrieve "mydb"?
        var mongoClient = new MongoClient(connectionString);
        var server = mongoClient.GetServer();
        var db = server.GetDatabase(dbName);

        container.Register<ICacheClient>(new MemoryCacheClient());
        container.Register<IUserAuthRepository>(new MongoDBAuthRepository(db, true));
    }
}

如何从web.config中检索连接字符串和数据库名称?

1 个答案:

答案 0 :(得分:1)

访问App或Web.Config appSettings的推荐方法是:

var appSettings = new AppSettings();
var connStr = appSettings.GetString("myDbConnectionString");

如果您将所有配置设置保留在<appSettings/>标记中,那就是这样。

要访问<connectionStrings>中保存的连接字符串,您可以使用ConfigUtils,例如:

var connStr = ConfigUtils.GetConnectionString("MyDb");