Ninject Scope和System.Threading.Timer

时间:2012-07-12 03:00:28

标签: c# asp.net-mvc-3 asynchronous ninject unit-of-work

如何在Timer任务上调用新的Ninject上下文? 很难将ninject范围配置到单元工作。如果我设置为InRequestScope(),则它不适用于非请求任务。所以我设置如下,以便我可以获得InThreadScope任务:

kernel.Bind<IUnitOfWork>().To<myEntities>().InScope(ctx => HttpContext.Current ?? StandardScopeCallbacks.Thread(ctx));

但是这样,当我设置一个计时器

Timer timer = new Timer(_ => DelayedDisconnect(chatUser.User.AuthorizationId), null, TimeSpan.FromSeconds(10), TimeSpan.FromMilliseconds(-1));

dbContext不会刷新新的数据库值。

public void DelayedDisconnect(string authorizationId)
    {
        var myChatUser = GetChatUserByClaimedIdentifier(authorizationId);

        if (!myChatUser.ChatClients.Any()) // old state (doesn't reflect database changes from 10 seconds ago).

那么......如何调用新的Ninject“context”来反映当前的状态/ db值?

1 个答案:

答案 0 :(得分:1)

您真的不应该在ASP.NET应用程序中运行后台任务。写一项服务来做到这一点。 http://haacked.com/archive/2011/10/16/the-dangers-of-implementing-recurring-background-tasks-in-asp-net.aspx

通过使用Windows服务,它变得非常简单。设置一个计时器,请求SomeProcessor从内核完成所有工作。现在您可以使用NamedScope扩展并定义处理器是某些对象的范围,例如UoW

kernel.Bind<SomeProcessor>().ToSelf().DefinesNamedScope("Processor");
kernel.Bind<IUoW>().To<UoW>().InNamedScope("Processor");
相关问题