Singleton service instantiated twice

I have a service and it’s service interface is registred as a singleton with the service decorator attribute.
[Service(ServiceType = typeof(IMySendService), Lifetime = DependencyLifetime.Singleton)]
The service is also implementing the IStartupTask because there is event handling in the service that needs to be registered at startup.
So far so good…

But the service is also used in a scheduled task and injected with DI to the task. And if I debug and set a breakpoint in the constructor of the service it’s beeing hit twice.

Shouldn’t there only be one instance of my service with that attribute?

Litium version: 7.2.3

The scheduled tasks that using the Litium.Foundation.Tasks.ITask interface is always created as transients. To work around and only create one instance of the service you need to wrap the service in an class that will be used as the task instance.

    public class MyTaskRunner : ITask, IStartupTask
    {
        private readonly MyInjectedService _service;

        public MyTaskRunner(MyInjectedService service)
        {
            _service = service;
        }

        public void ExecuteTask(SecurityToken token, string parameters)
        {
            _service.Execute();
        }

        public void Start()
        {
            _service.Execute();
        }
    }

    [Service(ServiceType = typeof(MyInjectedService), Lifetime = DependencyLifetime.Singleton)]
    public class MyInjectedService
    {
        public void Execute()
        {
            // do some stuff
        }
    }

Also the IStartupTask is in the older part of the code and will automatic register itself as singleton in the DI container without looking at the service-attribute.

Could you give an example on how the service should be wrapped in an class that will be used as the task instance? I did try to make a separate service that is used by the task and it’s injecting IMySendService. But didn’t got it working, still got multiple instances.

Se above example

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.