开发者

StructureMap dynamic set properties per HttpRequest

StructureMap Configuration

Is there a way in SM to dynamically inject property value only for the duration of a request then set the those property开发者_如何学Python back to default after the request is completed?

I'm specifically referring in the HttpRequest context.

I have a IDBAccessor interface and a DBAccessor concrete implementation.

IDBAccessor has a public property for connection string.

I want to set the connectionstring dynamically for each HttpRequest depending on some parameter that is passed in.

Is there an easy to accomplish this?

Thanks for the input.


I assume you have a class that encapsulates the logic to determine the connection string for each request. I'll call it ConnectionStringSource. You could then configure StructureMap like this:

ObjectFactory.Initialize(x =>
{
    x.For<IDBAccessor>().HybridHttpOrThreadLocalScoped()
        .Use(ctx =>
        {
            var connectionString = ctx.GetInstance<ConnectionStringSource>().GetConnectionString();
            var dbAccessor = new DBAccessor {ConnectionString = connectionString};
            return dbAccessor;
        });
});

public class ConnectionStringSource
{
    public string GetConnectionString()
    {
        // determine the connection string somehow
        return "connection string";
    }
}

The HybridHttpOrThreadLocalScoped call will make sure you get a new instance of DBAccessor for each HTTP request. And by using the Func<> overload of Use(), you can execute the code to determine and set the connection string during each request.

Note: You might want to just make the connection string a constructor parameter of DBAccessor instead of making it a property on the interface.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜