如何使用ravendb在mvc 3应用程序中设置多租户

时间:2012-03-01 13:24:18

标签: asp.net-mvc-3 c#-4.0 ravendb multi-tenant

我们通过以下方式使用RavenDb进行mvc3应用程序设置(在NoSql with RavenDb and Asp.net MVC的帮助下):

以下代码位于Global.asax

private const string RavenSessionKey = "RavenMVC.Session";
private static DocumentStore documentStore;

protected void Application_Start()
{
    //Create a DocumentStore in Application_Start
    //DocumentStore should be created once per 
    //application and stored as a singleton.
    documentStore = new DocumentStore { Url = "http://localhost:8080/" };
    documentStore.Initialise();
    AreaRegistration.RegisterAllAreas();
    RegisterRoutes(RouteTable.Routes);
    //DI using Unity 2.0
    ConfigureUnity();
}

public MvcApplication()
{
    //Create a DocumentSession on BeginRequest  
    //create a document session for every unit of work
    BeginRequest += (sender, args) => 
    {
      HttpContext.Current.Items[RavenSessionKey] = documentStore.OpenSession();
    }

    //Destroy the DocumentSession on EndRequest
    EndRequest += (o, eventArgs) =>
    {
        var disposable = 
                HttpContext.Current.Items[RavenSessionKey] as IDisposable;

        if (disposable != null)
            disposable.Dispose();
    };
}

//Getting the current DocumentSession
public static IDocumentSession CurrentSession
{
  get { return (IDocumentSession)HttpContext.Current.Items[RavenSessionKey]; }
}

我们现在想要设置应用程序以支持多租户。我们希望有两个文档存储:一个用于通用目的,一个用于系统数据库,另一个用于当前(登录)tennant。

根据我们目前的设置,我们如何实现这一目标?

修改:我们现在将应用程序配置如下:

我们在同一个documentStore上添加OpenSession(tenantid)BeginRequest(感谢Ayende的回答)

var tenant = HttpContext.Current.Request.Headers["Host"].Split('.')[0];
documentStore.DatabaseCommands.EnsureDatabaseExists(tenant);
HttpContext.Current.Items[RavenSessionKey] = 
                 documentStore.OpenSession(tenant);

因为我们正在使用Ninject进行DI,所以我们添加了以下绑定以确保我们使用正确的会话:

kernel.Bind<ISession>().To<Session>().WhenInjectedInto<UserService>();
kernel.Bind<ISession>().To<TenantSession>();

kernel.Bind<IDocumentSession>().ToMethod(ctx =>        
     MvcApplication.CurrentSession).WhenInjectedInto<Session>();

kernel.Bind<IDocumentSession>().ToMethod(ctx =>  
     MvcApplication.CurrentTenantSession).WhenInjectedInto<TenantSession>();

也许有更好的方法来配置ravendb和mvc的多租户?

1 个答案:

答案 0 :(得分:5)

AndrewF,

那么你将有两个会议。一个是defualt(OpenSession()),另一个是租户(OpenSession(TenantId)