【发布时间】: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)。无论哪种方式,newDispose 方法仍然会被触发。我输入了Debug.WriteLine,它永远不会被调用,除非我在AfterRequest管道上执行container.Resolve<IContext>().Dispose()。