相关疑难解决方法(0)

温莎 - 从容器中拉出瞬态物体

如何从容器中拉出瞬态物体?我是否必须在容器中注册它们并注入需要类的构造函数?将所有内容注入构造函数中感觉不太好.也只是为了一个类,我不想创建一个TypedFactory并将工厂注入需要的类.

我想到的另一个想法是根据需要"新"起来.但我也在我的Logger所有类中注入一个组件(通过属性).因此,如果我新建它们,我将不得不手动实例化Logger这些类.如何继续为我的所有课程使用容器?

记录器注入:我的大多数类都Logger定义了属性,除非存在继承链(在这种情况下,只有基类具有此属性,并且所有派生类都使用该属性).当这些通过Windsor容器实例化时,它们会将我的实现ILogger注入其中.

//Install QueueMonitor as Singleton
Container.Register(Component.For<QueueMonitor>().LifestyleSingleton());
//Install DataProcessor as Trnsient
Container.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 …
Run Code Online (Sandbox Code Playgroud)

.net dependency-injection castle-windsor ioc-container

57
推荐指数
1
解决办法
2万
查看次数