简体   繁体   中英

Multi-Tenancy in Webforms

I have had success in implementing multi-tenancy in MVC applications using Saaskit. The applications have a separate db for each tenant. I would like to implement something similar in a webforms project. Can anyone point me in the right direction? Is it even possible?

Must have:

  • Tenant detection based on domain/url
  • Must support db per tenant

Managed to use the new Unity support in Webforms 4.7.2 to support this:

public class TenantResolver : ITenantResolver
{

    public Tenant GetTenant()
    {

        var identifier = HttpContext.Current.Request.Url.Host.ToLower();

        return AllTenants().FirstOrDefault(x => x.HostNames.Any(a => a.Hostname.Contains(identifier)));

    }

    public List<Tenant> AllTenants()
    {

        // return list of tenants from configuration or seperate db

    }
}

In Startup

void Application_Start(object sender, EventArgs e)
{
    // Code that runs on application startup
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    var container = this.AddUnity();

    container.RegisterType<ITenantResolver, TenantResolver>();
    container.RegisterType<ApplicationContext, ApplicationContext>();

}

Example Page With Access to Tenant

public partial class About : Page
{
    readonly Tenant tenant;
    readonly ApplicationContext _context;

    public About(ITenantResolver tenantresolver, ApplicationContext context)
    {
        tenant = tenantresolver.GetTenant();

        _context = context;
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

Example db context with db per Tenant

public class ApplicationContext : DbContext
    {

        public ApplicationContext(ITenantResolver tenantResolver) : base(ConnectionStringResolver(tenantResolver)) {

        }

        private string ConnectionStringResolver(AppTenant appTenant)
        {

            var tenant = tenantResolver.GetTenant();

            if (tenant != null)
            {

                return tenant.ConnectionString;

            }

            throw new NullReferenceException("Tenant Not Found");

        }

    }

Default Membership API should suffice the requirements.

If not, consider http://www.asp.net/general/videos/how-do-i-create-a-custom-membership-provider

Refer tutorials> http://www.asp.net/security/tutorials

Videos http://www.asp.net/security/videos

Best practices are explained in the above tutorials.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM