TheCloudlessSky / Harbour.RedisSessionStateStore

A Redis based SessionStateStoreProvider written in C# using ServiceStack.Redis.
MIT License
166 stars 76 forks source link

Cannot specify Initial DB in config file #13

Closed shaunbowe closed 10 years ago

shaunbowe commented 10 years ago

I would like to be able to specify the initial database when setting up the connection. Here is the code to accomplish this. I was unable to create a pull request.

    public override void Initialize(string name, NameValueCollection config)
    {
        if (String.IsNullOrWhiteSpace(name))
        {
            name = "AspNetSession";
        }

        this.name = name;

        var sessionConfig = (SessionStateSection)WebConfigurationManager.GetSection("system.web/sessionState");

        sessionTimeoutMinutes = (int)sessionConfig.Timeout.TotalMinutes;

        lock (locker)
        {
            if (options == null)
            {
                SetOptions(new RedisSessionStateStoreOptions());
            }

            if (clientManagerStatic == null)
            {
                var host = config["host"];
                var clientType = config["clientType"];
                var initialDb = config["initialDb"];

                clientManager = CreateClientManager(clientType, host, initialDb);
                manageClientManagerLifetime = true;
            }
            else
            {
                clientManager = clientManagerStatic;
                manageClientManagerLifetime = false;
            }
        }

        base.Initialize(name, config);
    }

    private IRedisClientsManager CreateClientManager(string clientType, string host, string initialDb)
    {
        if (String.IsNullOrWhiteSpace(host))
        {
            host = "localhost:6379";
        }

        if (String.IsNullOrWhiteSpace(clientType))
        {
            clientType = "POOLED";
        }

        int database = 0;
        if (!int.TryParse(initialDb, out database)) {
            database = 0;
        }

        if (clientType.ToUpper() == "POOLED")
        {
            return new PooledRedisClientManager(database, host);
        }
        else
        {
            return new BasicRedisClientManager(database, host);
        }
    }
TheCloudlessSky commented 10 years ago

Hey!

The default options provided by the web.config are for really simple cases. If you require anything special I'd suggest using the SetClientManager static configuration (as seen in the README or the sample project).

private IRedisClientsManager clientManager;

protected void Application_Start()
{
    // Or use your IoC container to wire this up.
    this.clientManager = new PooledRedisClientManager(initialDb: 13, readWriteHosts: "localhost:6379");
    RedisSessionStateStoreProvider.SetClientManager(this.clientManager);
}

protected void Application_End()
{
    this.clientManager.Dispose();
}

Hope this helps!