【问题标题】:Do IDisposable objects get disposed at the end of a Nancy request using the RequestContainer?IDisposable 对象是否在使用 RequestContainer 的 Nancy 请求结束时被释放?
【发布时间】:2017-10-03 17:15:15
【问题描述】:

我正在将 DbContext 注册到 TinyIoCContainer 上,该 DbContext 已传递到 DefaultNancyBootstrapper 上的 ConfigureRequestContainer 方法中。

虽然这可以正常工作,但我注意到一旦请求完成,上下文中的 Dispose 方法就不会被调用。我希望 DbContext 在请求关闭连接(我们使用 SQLite)后被处理掉。

问:一次性实例实际上是在 TinyIoCContainer 内的请求结束时处置的吗?

引导程序

protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)
{
    base.ConfigureRequestContainer(container, context);

    container.Register<IContext>((_,__) => 
    {
        // Code here to get connection string
        return new Context(new SQLiteConnection(connString), true);
    });
}

上下文

public interface IContext : IDisposable
{
    ...
}

public class Context : DbContext, IContext
{
    ...

    public new void Dispose()
    {
        base.Dispose();  // This never gets called
    }
}

更新

标记的答案最终是正确的。我基本上不得不这样做:

if (string.IsNullOrEmpty(context.Request.UserHostAddress))
{
    container.Register<IContext>((_,__) => null);
}
else
{
    // Get username from request headers
    // Build up SQLite connection string based off username
    var dbContext = new Context(new SQLiteConnection(connString));
    container.Register<IContext>(dbContext);
}

【问题讨论】:

  • 你为什么不测试一下?在您的 Dispose 方法中放入跟踪行。但是,public new void Dispose() 不是 void IDisposable.Dispose()。这就是new 的意思。
  • 我已经通过在 base.Dispose 行上放置一个断点来测试它 - 如果我在 using 语句中使用上下文,它会被调用,所以我认为它也会在请求后被调用,虽然我确实怀疑我可能在滥用它!我会尝试添加跟踪线,谢谢。
  • 你真的想用override替换工作new
  • @Aron 我无法覆盖 Dispose,尽管我可以覆盖 Dispose(bool disposing)。无论哪种方式,new Dispose 方法仍然会被触发。我输入了Debug.WriteLine,它永远不会被调用,除非我在AfterRequest 管道上执行container.Resolve&lt;IContext&gt;().Dispose()

标签: c# .net nancy tinyioc


【解决方案1】:

我认为这是因为您使用的是手动工厂注册,它希望您自己控制生命周期。无论如何,您可能不想使用它,因为每次您使用那里的代码请求一个新上下文时,您都会创建一个新上下文 - 将其切换到实例注册,您应该没问题。

container.Register<IContext>(new Context(new SQLiteConnection(connString), true));

【讨论】:

  • 我们需要工厂注册,因为请求头中发送的用户名决定了使用哪个数据库,不幸的是,第一次调用该方法时头不可用。我会假设 RequestContainer 上的任何注册都会持续请求的生命周期,但我一定假设错了!刚刚发现这个github.com/grumpydev/TinyIoC/wiki/Registration---lifetimes 提到了一个扩展,它可以用来指定每个请求的生命周期——我会试一试的。
【解决方案2】:

没有经常使用 TinyIoC,但是这个页面说每个请求的注册是不同的,不确定是否应该总是这样。

https://github.com/grumpydev/TinyIoC/wiki/Registration---lifetimes

【讨论】:

    猜你喜欢
    • 2013-01-04
    • 1970-01-01
    • 2011-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-16
    • 1970-01-01
    相关资源
    最近更新 更多