当HttpContext.Current不存在时,依赖注入处理案例

时间:2013-10-30 20:55:30

标签: asp.net multithreading nhibernate dependency-injection unity-container

我有一个ASP.NET MVC应用程序,在我的Application_Start事件中,我有以下代码:

container.RegisterType<ISessionFactory>(new ContainerControlledLifetimeManager(), new InjectionFactory(c => {
    return BuildSessionFactory();
}));
container.RegisterType<ISession>(new PerRequestLifetimeManager<ISession>(), new InjectionFactory(c => {
    return c.Resolve<ISessionFactory>().OpenSession();
}));

会话工厂(ISessionFactory)的生命周期为应用程序。会话(ISession)的生命周期为ASP.NET请求。我还在Application_EndRequest事件中处理会话。这允许我在整个应用程序中注入ISession,它按预期工作。

我现在正在尝试将任务调度构建到我的应用程序中。我已将以下代码添加到Application_Start事件中:

var timer = new System.Timers.Timer(5000);
timer.Elapsed += (sender, e) => {
    var thread = new Thread(new ThreadStart(() => {
        var service = DependencyResolver.Current.GetService<ISomeService>();

        ...
    }));
    thread.Start();
};
timer.Enabled = true;

这应该每5秒运行一次。 ISomeService的实现在构造函数中注入了ISession,我不希望更改此类。当我试图在HttpContext.Current为空的线程中尝试解析ISession并因此抛出异常时,我的问题出现了。我想知道如何注册会话来处理这种情况。我很感激你的帮助。

谢谢

这是我的PerRequestLifetimeManager类,它有助于:

public class PerRequestLifetimeManager<T> : LifetimeManager {
    public override object GetValue() {
        return HttpContext.Current.Items[typeof(T).AssemblyQualifiedName];
    }

    public override void RemoveValue() {
        HttpContext.Current.Items.Remove(typeof(T).AssemblyQualifiedName);
    }

    public override void SetValue(object newValue) {
        HttpContext.Current.Items[typeof(T).AssemblyQualifiedName] = newValue;
    }
}

1 个答案:

答案 0 :(得分:1)

解析ISessionFactory并自行管理会话的生命周期。

var timer = new System.Timers.Timer(5000);
timer.Elapsed += (sender, e) => {
var thread = new Thread(new ThreadStart(() => {
    var service = DependencyResolver.Current.GetService<ISessionFactory>();
    using(var session = service.OpenSession())
    {
        //do something with session
    }

    ...
}));
thread.Start();
};
timer.Enabled = true;

编辑: Unity具有多个容器实例的功能,可以具有不同的配置。这样,您就可以为“服务”

配置不同的生命周期管理器