通过用户参数解析依赖关系

时间:2013-03-13 11:05:38

标签: c#-4.0 dependency-injection

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

真正的问题是,当应用程序启动时,object参数始终是未知的,因此我现在无法注册任何依赖项,也无法解决它们。

相反,例如,当我需要使用一些本身需要加载某些依赖项的类时,我知道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();

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

1 个答案:

答案 0 :(得分: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看起来像parameter object。依赖注入不会消除需要方法参数的需要。数据仍应通过方法传递。