溫莎-從容器中提取瞬變對(duì)象我如何從容器中拉出本質(zhì)上是短暫的物體?我是否必須將它們注冊(cè)到容器中并插入所需類(lèi)的構(gòu)造函數(shù)中?將所有內(nèi)容都注入構(gòu)造函數(shù)并不好。也只是為了一個(gè)類(lèi),我不想創(chuàng)建一個(gè)TypedFactory并將工廠注入需要類(lèi)。我想到的另一個(gè)想法是“新的”他們是根據(jù)需要來(lái)的。但我也在注射Logger將組件(通過(guò)屬性)添加到我的所有類(lèi)中。因此,如果我更新了它們,就必須手動(dòng)實(shí)例化Logger在那些課上。如何繼續(xù)為我的所有類(lèi)使用容器?記錄器注入:我的大多數(shù)班級(jí)都有Logger屬性定義,除非存在繼承鏈(在這種情況下,只有基類(lèi)具有此屬性,所有派生類(lèi)都使用該屬性)。當(dāng)它們通過(guò)溫莎容器實(shí)例化時(shí),它們將得到我的ILogger注射到他們體內(nèi)。//Install QueueMonitor as SingletonContainer.Register(Component.For<QueueMonitor>().LifestyleSingleton());
//Install DataProcessor as TrnsientContainer.Register(Component.For<DataProcessor>().LifestyleTransient());
Container.Register(Component.For<Data>().LifestyleScoped());public class QueueMonitor{
private dataProcessor;
public ILogger Logger { get; set; }
public void OnDataReceived(Data data)
{
//pull the dataProcessor from factory
dataProcessor.ProcessData(data);
}}public class DataProcessor{
public ILogger Logger { get; set; }
public Record[] ProcessData(Data data)
{
//Data can have multiple Records
//Loop through the data and create new set of Records
//Is this the correct way to create new records?
//How do I use container here and avoid "new"
Record record = new Record(/*using the data */);
...
//return a list of Records
}}public class Record{
public ILogger Logger { get; set; }
private _recordNumber;
private _recordOwner;
public string GetDescription()
{
Logger.LogDebug("log something");
// return the custom description
}}問(wèn)題:如何創(chuàng)建新的Record對(duì)象而不使用“new”?QueueMonitor是Singleton,鑒于Data是“范圍”。我怎么注射Data進(jìn)OnDataReceived()方法?
3 回答

哈士奇WWW
TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超6個(gè)贊
我同意您在這里所說(shuō)的一切,我也不同意僅僅為了記錄和重新拋出而捕獲異常,因?yàn)槲艺J(rèn)為應(yīng)用程序域中應(yīng)該有一個(gè)中心點(diǎn)來(lái)執(zhí)行此操作,但是我確實(shí)覺(jué)得有時(shí)候您需要捕獲一個(gè)特定的異常,比如SQLException來(lái)重試該操作。
- 3 回答
- 0 關(guān)注
- 226 瀏覽
添加回答
舉報(bào)
0/150
提交
取消