Handling Datacontext Operations in Timer_Elapsed using StructureMap

Please what is the best way to wire up/use a datacontext object in a timer_elapsed event. I have a datacontext object within a timer_elapsed that runs perfectly the first time but does nothing on subsequent calls of the timer_elapsed event. I understand a new instance is created for every call of the elapsed event on a threadpool thread. How do I control this behaviour or at least get my code to run consistently. Thanks.

This is my structure map config

ForRequestedType<BulkSMSDataContext>()
            .TheDefaultIs(() => new BulkSMSDataContext())
            .CacheBy(InstanceScope.Hybrid);

This is my timer implementation

void _timerSendScheduledMessages_Elapsed(object sender, ElapsedEventArgs e)
    {
        DateTime currentUTC = DateTime.UtcNow.AddSeconds(-DateTime.UtcNow.Second).AddMilliseconds(-DateTime.UtcNow.Millisecond);

        var msgToSend = from c in _messageRepository.GetMessages(MessageTypes.Scheduled)
                        where c.Time == currentUTC
                        select c;


        foreach (var msg in msgToSend)
        {
            int scheduledMsgID = msg.MessageID;
            Response res = _messageService.Send(msg);
            _messageRepository.DeleteScheduledMessage(scheduledMsgID);
        }
    }

Answers


To better control the scope I would change the elapsed event to create a new _messageRepository each time it's called, assuming you pass the datacontext to the _messageRepository that is. Then let structuremap inject your datacontext into it.

Otherwise you end up with a poorly defined unit of work which tends to bring up scoping issues like the one you are having.

Without seeing you implementation though, hard to tell exactly.


Need Your Help

bulkloader.py --dump without authentication

python google-app-engine backup

Is there some way or using the bulkloader.py dump and restore functionality without authentication?

ember cli url not working on server with manual return key (versus link-to)

ember.js ember-cli

An ember cli site was deployed onto a server and it works fine. Links via {{link-to}} all work beautifully.