Instances cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it has already been disposed.
使用OWIN和AutoFac for DI的WebApi应用程序编写集成测试,产生Instances cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it has already been disposed.错误。
解决方案:
主要是因为Autofac的IContainer是局部变量,它已被释放,所以应设置一个全局变量来保存它,例如在Global.asax中:
public static IContainer Container => _container ?? (_container = BuildContainer()); 在这种情况下,_container并非为空,而是处于“已处置”状态。如果您无条件重新创建它,则它应该可以工作。(我还不熟悉C#6语法,因此这可能并不完全正确) public static IContainer Container => _container = BuildContainer(); 替代答案: 在自托管的OWIN Web API中,如何在关闭时运行代码? public class Startup { public void Configuration(IAppBuilder app) { var context = new OwinContext(app.Properties); var token = context.Get<CancellationToken>("host.OnAppDisposing"); if (token != CancellationToken.None) { token.Register(() => { // code to run // null out disposable resources }); } } }
另外要注意的是Autofac注册服务的顺序,可能需要放在Application_Start的最前面。