0

我经常需要使用一些本身必须加载一些依赖项才能工作的类。但是,我的组件可以有多个具体的依赖实现,它会根据某些对象参数选择一个,而不是另一个。

真正的问题是应用程序启动时对象参数总是未知的,所以我现在无法注册任何依赖项,也无法解决它们。

相反,例如,当我需要使用某个本身需要加载某些依赖项的类时,我知道使用的对象参数concreteBuilder以便返回给我适当的实现:

interface ISample { }

class ParamForBuildSomeISampleImplementation
{
    // this instance cannot be create by my startUpApplication - Container - Resolver.
    // Instead, all time dependency is required (buttonClick, pageLoad and so on), this class can be instantiated.
}

class Sample1 : ISample 
{
    // some implementation
}

class Sample2 : ISample
{
    // some other implementation
}

class MyISampleFactory
{
    // Build ISample
    public ISample Build(ParamForBuilderISample obj)
    {
        // if obj.someProperty == ".." return new Sample1();
        // else if obj.someProperty == "--" return new Sample2();
        // else if ...
    }
}

class NeedsDependency
{
    ISample _someSample;
    public NeedsDependency(ISample someSample)
    {
        _someSample = someSample;
    }
}


// *** Controllor - ApplicationStartup - other ***
// Here I have not idea how to build ISample dependency

@@ EDIT 
// *** button click event handler ***
// Ok, here I know how to create ParamForBuilderISample, 
// hence I can call MyISampleFactory, then, I can Use NeedDependency class:
ParamForBuilderISample obj = new ...
obj.SomeProperty = ...
obj.otherSomeProperty = ...
ISample sample = MyISampleFactory.Build(obj);
NeedDependency nd = new NeedDependency(sample);
// perfect, now my buttonClick can execute all what it wants
nd.DoSomething();
nd.DoOtherStuff();

我的场景适合依赖注入模式吗?如果是真的,我真的不知道如何构建我的模式。

4

1 回答 1

0

与其使用构造函数注入来传递此“运行时依赖项”,不如使用方法注入。这甚至可以完全消除对工厂的需求:

private readonly ISample sample;

public MyController(ISample sample) {
    this.sample = sample;
}

public string button_click_event_handler(object s, EventArgs e) {
    ParamForBuilderISample obj = new ...
    obj.SomeProperty = ...
    obj.otherSomeProperty = ...

    this.sample.DoSomething(obj);
}

您仍然需要在某个地方切换,但是您可以实现代理,而不是拥有工厂ISample

public class SampleProxy : ISample
{
    private readonly Sample1 sample1;
    private readonly Sample2 sample2;

    public SampleProxy(Sample1 sample1, Sample2 sample2) {
        this.sample1 = sample1;
        this.sample2 = sample2;
    }

    public void DoSomething(ParamForBuilderISample param) {
        this.GetSampleFor(param).DoSomething(param);
    }

    private ISample GetSampleFor(ParamForBuilderISample param) {
        // if obj.someProperty == ".." return this.sample1;
        // else if obj.someProperty == "--" return this.sample2;
        // else if ...
    }
}

ParamForBuilderISample看起来像一个参数对象。依赖注入并没有消除对方法参数的需要。数据仍应通过方法传递。

于 2013-03-13T12:38:17.867 回答