Most painless multi-tenancy implementation using ASP.NET, NHibernate / Fluent NHibernate

江枫思渺然 提交于 2019-12-03 20:14:45

I've been looking for the same thing for a small project of mine that's still in planning phase. The most complete implementation of using a single database that I came upon is written by Michael Valenty in his blog post: Bolt-on Multi-Tenancy in ASP.NET MVC with Unity and NHibernate: Part II – Commingled Data. He's also using global filters.

Just for the sake of completeness, here are the mappings he used:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
    <filter-def name="tenant">
        <filter-param name="id" type="System.Int32" />
    </filter-def>
</hibernate-mapping>

And for each entity:

<class name="User" table="[user]">
    <id name="Id" column="user_id">
        <generator class="identity" />
    </id>

    <property name="Username" />
    <property name="Email" />

    <filter name="tenant" condition="tenant_id = :id" />
</class>

After that, he uses his IoC container of choice to inject the parameter value to instance of ISession.

session.EnableFilter("tenant").SetParameter("id", c.Resolve<Tenant>().Id);

There's also an interceptor to implement - to write the value of current tenant id when saving the entity (OnSave method), and also to check whether the given entity belongs to current tenant when loading the entity by id (OnLoad method). OnLoad override is necessary because tenant filter won't be applied when loading entity by id.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!