Mih*_*gos 12 c# asp.net-mvc dependency-injection inversion-of-control autofac
问题:
假设班级:
public class MyAwesomeClass
{
private IDependCls _dependCls;
public MyAwesomeClass(IDependCls dependCls)
{
_dependCls = dependCls;
}
}
Run Code Online (Sandbox Code Playgroud)
在其他地方我需要获得该类的实例,如下所示:
public class SomewhereElse
{
public void AwesomeMethod()
{
//...
// AwesomeStuff
//...
var GetErDone = new MyAwesomeClass(); // PROBLEM! No constructor with 0 arguements
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,我
建议的解决方案1:
A)必须制作一个额外的构造来解决依赖关系吗?例如:
public MyAwesomeClass() // new constructor
{
_dependCls = DependencyResolver.Current.GetService<IDependCls>();
}
public class SomewhereElse
{
public void AwesomeMethod()
{
var GetErDone = new MyAwesomeClass(); // IT WORKS!!
}
}
Run Code Online (Sandbox Code Playgroud)
建议的解决方案2:
B)使用AwesomeMethod之前 的旋转变压器var GetErDone
public class SomewhereElse
{
public void AwesomeMethod()
{
var depCls = _dependCls = DependencyResolver.Current.GetService<IDependCls>();
var GetErDone = new MyAwesomeClass(depCls); // IT WORKS!!
}
}
Run Code Online (Sandbox Code Playgroud)
Autofac解决方案?
C)其他一些Autofac方式?
寻找最佳实践,以及尽可能好的Autofac解决方案.我认为第一种方式是最糟糕的,因为可选的依赖性可能会导致很多混乱.
摘要:
我如何获得一个new MyAwesomeClass()当MyAwesomeClass有依赖性?
看看Composition Root模式.
你是对的,提升依赖性解决方案只会将问题转移到另一个地方.但是,如果继续在对象图中向上移动,则会到达应用程序的入口点.在那里,您将构建对象图.
将其与Service Locator反模式进行比较(在您的情况下使用客户端类中的DependencyResolver),您将看到Composition Root是一个出色的解决方案.