Base solution for your next web application
Open Closed

Access appservice from _Viewstart? #2001


User avatar
0
bubba created

I'm trying to use different layouts per tenant. The layouts are stored in database, but since layouts are set in _Viewstart.cshtml I am having trouble. How can I access an appservice from _Viewstart.cshtml?

If I don't set the layout in _viewstart I would have to set it on every "return View(...)" and that is not a good option as I have hundreds of those.

I can access a static method in a controller from _Viewstart like this:

string theme = Gentide.Web.Controllers.TenantsController.GetTenantTheme(HttpContext.Current.Request.Url.Host);

    Layout = "~/Views/Shared/_Layout" + theme + ".cshtml";

But since it is static I cannot access any appservice instances that that controller have injected :( ... which also means I have to access the database directly (not using repositories), for example:

db.Tenants.FirstAsync(x => x.TenancyName == host)

and which also means that I cannot use the CacheManager. As you can see it's not really a good solution.

Here is what I would like to do:

string theme = _tenantAppservice.GetCurrentTenantTheme();

or perhaps directly if that would be easier for some reason:

Tenant tenant = await CacheManager
                   .GetCache(MyConsts.MyCache)
                   .Get(HttpContext.Current.Request.Url.Host + MyConsts.TENANT_CACHE_KEY, async () => await _tenantManager.GetTenant(HttpContext.Current.Request.Url.Host));
string theme = tenant.Theme;

Any advice is appreciated!


1 Answer(s)
  • User Avatar
    0
    bubba created

    I solved it finally. For anyone else looking for an answer, here is the solution: Somehow I had missed this in the documentation:

    If you are in a static context or can not inject IIocManager, as a last chance, you can use singleton object IocManager.Instance everywhere.

    So now I can do this:

    ITenantAppservice tenantAppservice = IocManager.Instance.Resolve<TenantAppservice>();
    string theme = tenantAppservice.GetCurrentTenantTheme();
    

    Sweet!