How to get the instance of an injected dependency, by its type using Umbraco.Core.Composing (Umbraco 8)

219 Views Asked by At

I need to find a way to get an instance of DataProcessingEngine without calling it's constractor. I am trying to find a way to do so using the registered DataProcessingEngine in composition object (please see the following code). But I could not find a way to do so. Anyone have a suggestion? Thanks in advance.

public class Composer : IUserComposer
{
    public void Compose(Composition composition)
    {
        composition.Register<IDataProcessingEngine, DataProcessingEngine>(Lifetime.Singleton);
        //DataProcessingEngine dataProcessing = compostion.Resolve<IDataProcessingEngine>()??//no resolve function exists in Umbraco.Core.Composing
        SaveImagesThread(dataProcessingEngine);
    }

    public Task SaveImagesThread(IDataProcessingEngine dataProcessingEngine)//TODO - decide async
    {
        string dataTimerTime = WebConfig.SaveProductsDataTimer;

        double time = GetTimeForTimer(dataTimerTime);
        if (time > 0)
        {
            var aTimer = new System.Timers.Timer(time); 
            aTimer.Elapsed += new ElapsedEventHandler(dataProcessingEngine.SaveImages);
            aTimer.Start();
        }
        return default;
    }
}
1

There are 1 best solutions below

0
On

For all of you who are looking for a way to call a function (that's defined in another class in your code, an Engine or ...) from the composer(where the app starts) and want to avoid calling this function's class' constractor. I've found another way to do so:

public class QueuePollingHandler
    {
        [RuntimeLevel(MinLevel = RuntimeLevel.Run)]
        public class SubscribeToQueuePollingHandlerComponentComposer : 
        ComponentComposer<SubscribeToQueuePollingHandler>
        { }
        public class SubscribeToQueuePollingHandler : IComponent
        {
            private readonly IDataProcessingEngine _dataProcessingEngine;

            public SubscribeToQueuePollingHandler(IDataProcessingEngine 
            dataProcessingEngine)
            {
                _dataProcessingEngine = dataProcessingEngine;
                SaveImagesThread(_dataProcessingEngine);
            }

            public void SaveImagesThread(IDataProcessingEngine 
            dataProcessingEngine)
            {
             ....
            }
   }

And the logic explenation: You create a class (SubscribeToQueuePollingHandlerComponentComposer from the example) and define its base class to be ComponentComposer<Class_that_inherits_IComponent>. And when you start the application you could see that it gets to the registered class' constractor (SubscribeToQueuePollingHandler constructor).

That's the way that I found to be able to call a function right when the application starts without needing to call its class constractor and actualy use dependency injection.