Copied to clipboard

Flag this post as spam?

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


  • Roy Berris 89 posts 578 karma points c-trib
    Oct 28, 2021 @ 14:18
    Roy Berris
    0

    Get reference to the light inject service container

    We can access the light inject service container from a Composition. But we can only access that during start-up.

    I have a taskrunner which runs in the background. This will execute a ISyncService.StartSync() every hour. Problem is that I want to manage my own scope with the lightinject container.

    If I have the container we can do:

    using (var scope = _container.BeginScope())
    {
        var umbracoContextFactory = scope.GetInstance<IUmbracoContextFactory>();
        var syncService= scope.GetInstance<ISyncService>();
    
        using (umbracoContextFactory.EnsureUmbracoContext())
        {
            await syncService.StartSync();
        }
    }
    

    But ofcourse I can't get a reference to the lightinject container. When injecting the services from the component, which starts the task runner. I get one instance, but it's important that I create new instances on each run. And when the run is done, the dependencies get disposed properly because we are working with a DbContext from EF.

    Does anyone know how to get a reference to the light inject service container at runtime. Or how I can get these dependencies another way, which will get disposed properly.

  • Roy Berris 89 posts 578 karma points c-trib
    Oct 28, 2021 @ 15:07
    Roy Berris
    100

    After some more research I found out how to get the container.

    I can do Current.Factory.Concrete as LightInject.ServiceContainer. But this is useless because when I try to BeginScope() I'll get an exception that it is not started in a web context.

    Why does it require a web context?

  • Arjan H. 226 posts 463 karma points c-trib
    Dec 07, 2021 @ 16:07
    Arjan H.
    0

    Hi Roy, did you manage to resolve this issue? I'm also trying to inject a custom service that uses DbContext (EF) into a background task component. But I'm getting the following boot failed error:

    System.InvalidOperationException: Attempt to create a scoped instance without a current scope.
    
  • Alexandru Rustin 7 posts 87 karma points
    Jul 07, 2022 @ 16:06
  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies