Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at

  • Andrii 4 posts 105 karma points
    Jul 31, 2019 @ 08:00

    DI with Lifetime.Request works per thread

    I am using umbraco containers for DI, and it works pretty well exapt the thing that Lifetime.Request is not working. I have lot of custom services based on generic repositories which have to use 1 opened db context for entire request. So i register db context in container like this:

        composition.Register<EntityContext>((x) => EntityContext.Instance(), Lifetime.Request);
        composition.Register(typeof(IDatabaseTransaction), typeof(DatabaseTransaction), Lifetime.Request);
        composition.Register(typeof(IUnitOfWork), typeof(UnitOfWork), Lifetime.Request);
        composition.Register(typeof(IRepository<>), typeof(Repository<>), Lifetime.Request);

    ConfigureForWeb() - has no effect, with or without - same result. So every single Repository gets new db context instance, db transaction and unit of work too, so i have ~35 different db contexts for single request. So unitofwork and db transaction cant handle db updates at all, as concept breaks. Any idea why Lifetime.Request is not working as expected?

    Using those container methods, all or one:

    var container = composition.Concrete as ServiceContainer;

    couses runtime exception: Container.ScopeManagerProvider is not MixedLightInjectScopeManagerProvider

    This exception is generated by Umbraco.Core.Composing.LightInject.LightInjectContainer method, line 268, and it executes just fine during IUserComposer setup, but throws exception at runtime, so it is executed more than once:

    public void EnablePerWebRequestScope()
                if (!(Container.ScopeManagerProvider is MixedLightInjectScopeManagerProvider smp))
                    throw new Exception("Container.ScopeManagerProvider is not MixedLightInjectScopeManagerProvider.");

    All dependensies registered with fluent LightInject api inside Composition, or using Composition.Register - which use Lifetime.Request or PerRequestLifeTime - gets disposed before being injected into controller and services, also create as many instances as requested, instead 1 instance per request.

    Building own container with all dependencies for DependencyResolver - breaks umbraco backoffice totally, so it is not an option too.

    Any ideas why? or any workaround? Would appreciate any help. Standart documentation doesnt help

    Link to issue on Umbraco-CMS github:

  • Kenn Jacobsen 133 posts 791 karma points MVP 4x c-trib
    Aug 03, 2019 @ 05:46
    Kenn Jacobsen

    I believe you need to use PerScopeLifetime for this. See and for documentation.

Please Sign in or register to post replies

Write your reply to: