Search code examples
sitecoreglass-mapper

Glass context database null


I'm experiencing an issue with Glass Mapper in my current project that I haven't encountered before.

Directly after Sitecore has been initialized, the Database property in my GlassContext (ISitecoreContext) is null.

// After Sitecore initialization, sometimes the glass context database is not initialized yet.
if (this.glassContext == null || this.glassContext.Database == null)
{
    this.glassContext = DependencyInjection.Container.Resolve<ISitecoreContext>();

    // Now I have a valid this.glassContext.Database ...
}

When I ask my DI framework (Windsor, so Glass' default) for an instance, it returns me one with a valid Database property.
For the time-being I'm doing this check before retrieving any items and it only needs this check one time (after that it's good until the next initialization), but would really like to know what is causing this.

Probably interesting to know: all item requests (getting items, casting items, etc.) are done through one service which gets the ISitecoreContext initialized in its constructor.
The ItemService has lifetime Singleton, the ISitecoreContext has lifetime Transient


Solution

  • I think that your ItemService was first time injected before Sitecore has a valid context, therefore Glass also cannot be have a valid context (database). Because your ItemService has a Singleton lifetime, the constructor is only called once and also the resolving of ISitecoreContext is done once. This means, if your ItemService is resolved the first time before Sitecore has a valid context, then your glassContext will be null. After you manually set the glassContext property in the Singleton instance, the next time it won't be null (but maybe not valid because you are in another request).

    I would suggest you setting both dependencies either to Transient or to PerWebRequest.