Skip to content

Instantly share code, notes, and snippets.

@stevenknox
Last active October 10, 2016 22:11
Show Gist options
  • Save stevenknox/1e515a4fdb7edd748e7cfa1cb0f190e4 to your computer and use it in GitHub Desktop.
Save stevenknox/1e515a4fdb7edd748e7cfa1cb0f190e4 to your computer and use it in GitHub Desktop.
UseTenant TypeFilterAttribute for SaaSKit - https://github.com/saaskit/saaskit/
public class UseTenantAttribute : TypeFilterAttribute
{
public UseTenantAttribute() : base(typeof(UseTenantFilter))
{
}
private class UseTenantFilter : IActionFilter
{
readonly AppTenant _tenant;
public UseTenantFilter(ITenant<AppTenant> tenant)
{
this._tenant = tenant.Value;
}
public void OnActionExecuting(ActionExecutingContext context)
{
if (context.Controller is ITenantController)
{
((ITenantController)context.Controller).Tenant = _tenant;
}
else
{
context.Controller.ViewBag.Tenant = _tenant;
}
}
public void OnActionExecuted(ActionExecutedContext context)
{
}
}
}
interface ITenantController
{
IAppTenant Tenant { get; set; }
}
//Using standard controller and returning Tenant within ViewBag
public class TestActionController : Controller
{
[UseTenant]
public IActionResult Index()
{
AppTenant tenant = (AppTenant)ViewBag.Tenant;
return View();
}
}
//Using ITenantController interface and setting AppTenant property
[UseTenant]
public class TestController : Controller, ITenantController
{
public AppTenant Tenant { get; set; }
public IActionResult Index()
{
ViewBag.TenantName = Tenant.Name;
return View();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment