2017-05-05 42 views
2

我正在註冊一個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); 
} 
+0

你爲什麼不測試它?將跟蹤行放入Dispose方法中。然而,'public new void Dispose()'不是'void IDisposable.Dispose()'。這就是'new'的意思。 – Aron

+0

我已經通過在'base.Dispose'行上放置了一個斷點來測試它 - 如果我在'using'語句中使用上下文,它會被調用,所以我想它也會在請求後被調用,雖然我懷疑我可能會濫用它!我會嘗試添加一條跟蹤線,謝謝。 – Tom

+0

你真的想用'override'替換'new'工作。 – Aron

回答

1

我認爲它是因爲你使用手動工廠登記,預計你自己控制的壽命。不管怎樣,你可能不想使用它,因爲每當你用你有的代碼請求一個新的上下文時,你都會創建一個新的上下文 - 將它切換到實例註冊,你應該沒問題。

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

我們需要工廠註冊,因爲在請求頭中發送的用戶名決定了要使用哪個數據庫,不幸的是頭在第一次調用該方法時不可用。我假設在RequestContainer上的任何註冊都會持續請求的生命週期,但我一定錯了! 剛剛發現這個https://github.com/grumpydev/TinyIoC/wiki/Registration---lifetimes它提到了一個擴展,可以用來指定每個請求的生命週期 - 我會給它一個去。 – Tom

相關問題