IDisposable 对象是否在使用 RequestContainer 的 Nancy 请求结束时被释放?
Do IDisposable objects get disposed at the end of a Nancy request using the RequestContainer?
我正在将 DbContext 注册到 TinyIoCContainer
上,该 TinyIoCContainer
已传递到 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);
}
没有经常使用 TinyIoC,但是这个页面说每个请求的注册是不同的,不确定是否应该总是这样。
https://github.com/grumpydev/TinyIoC/wiki/Registration---lifetimes
我认为是因为您使用的是手动工厂注册,它希望您自己控制寿命。您可能无论如何都不想使用它,因为每次您使用现有代码请求一个上下文时都会创建一个新上下文 - 将其切换到实例注册,您应该没问题。
container.Register<IContext>(new Context(new SQLiteConnection(connString), true));
我正在将 DbContext 注册到 TinyIoCContainer
上,该 TinyIoCContainer
已传递到 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);
}
没有经常使用 TinyIoC,但是这个页面说每个请求的注册是不同的,不确定是否应该总是这样。
https://github.com/grumpydev/TinyIoC/wiki/Registration---lifetimes
我认为是因为您使用的是手动工厂注册,它希望您自己控制寿命。您可能无论如何都不想使用它,因为每次您使用现有代码请求一个上下文时都会创建一个新上下文 - 将其切换到实例注册,您应该没问题。
container.Register<IContext>(new Context(new SQLiteConnection(connString), true));