溫莎 - 從容器中拉出瞬態(tài)物體如何從容器中拉出瞬態(tài)物體?我是否必須在容器中注冊它們并注入需要類的構造函數(shù)?將所有內容注入構造函數(shù)中感覺不太好。也只是為了一個類,我不想創(chuàng)建一個TypedFactory并將工廠注入需要的類。我想到的另一個想法是根據(jù)需要“新”起來。但我也在我的Logger所有類中注入一個組件(通過屬性)。因此,如果我新建它們,我將不得不手動實例化Logger這些類。如何繼續(xù)為我的所有課程使用容器?記錄器注入:我的大多數(shù)類都Logger定義了屬性,除非存在繼承鏈(在這種情況下,只有基類具有此屬性,并且所有派生類都使用該屬性)。當這些通過Windsor容器實例化時,它們會將我的實現(xiàn)ILogger注入其中。//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
}}問題:如何在Record不使用“new”的情況下創(chuàng)建新對象?QueueMonitor是Singleton,而是Data“Scoped”。我怎樣才能注入Data到OnDataReceived()方法?
- 1 回答
- 0 關注
- 290 瀏覽
添加回答
舉報
0/150
提交
取消