如果我把Lazy放在我的对象的构造函数中,并且X没有在容器中注册,我得到了依赖性解析异常。Autofac可选/懒惰依赖
为什么我会得到这个异常?我不喜欢它,因为我无法在运行时选择组件。示例用例:
class Controller
{
public Controller(Lazy<A> a, Lazy<B> b) { /* (...) */ }
Lazy<A> a;
Lazy<B> b;
public IActionResult Get(){
if(someConfig)
return Json(a.Value.Execute());
else
return Json(b.Value.Execute());
}
}
为此,我需要注册两个组件A和B.即使从未使用B,我的程序也会失败。我希望B是可选的,并且仍由autofac管理。
这是更大的问题,如果我有组件列表,并希望只使用一个。例如:
class Controller
{
Controller(IEnumerable<Component> components) { /* (...) */ }
IActionResult Get()
{
return components.First(n => n.Name == configuredComponent).Execute();
}
}
我不再是异常是没有注册的东西,但仍然是一切都构造。而且使用起来会很尴尬。