我经常需要使用一些本身必须加载一些依赖项才能工作的类。但是,我的组件可以有多个具体的依赖实现,它会根据某些对象参数选择一个,而不是另一个。
真正的问题是应用程序启动时对象参数总是未知的,所以我现在无法注册任何依赖项,也无法解决它们。
相反,例如,当我需要使用某个本身需要加载某些依赖项的类时,我知道使用的对象参数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();
我的场景适合依赖注入模式吗?如果是真的,我真的不知道如何构建我的模式。