我正在註冊一個DbContext到TinyIoCContainer
上,這個數據傳遞到DefaultNancyBootstrapper
上的ConfigureRequestContainer
方法中。是否使用RequestContainer將一個IDisposable對象置於Nancy請求的末尾?
雖然這工作正常,但我注意到上下文中的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'的意思。 – Aron
我已經通過在'base.Dispose'行上放置了一個斷點來測試它 - 如果我在'using'語句中使用上下文,它會被調用,所以我想它也會在請求後被調用,雖然我懷疑我可能會濫用它!我會嘗試添加一條跟蹤線,謝謝。 – Tom
你真的想用'override'替換'new'工作。 – Aron