Managing Dependency Injection in C# with Autofac用手依赖注入:手工VS autofac
var di = new EmployeeObserver(employees, new Printer(Console.Out));
di.FindExperts();
与autofac的解释却是非常简洁的方式与downloadable source code
依赖注入:
ContainerBuilder autofac = new ContainerBuilder();
autofac.Register(o => new EmployeeObserver(o.Resolve<IList<Employee>>(), o.Resolve<IPrinter>()));
autofac.RegisterType<Printer>().As<IPrinter>();
autofac.RegisterInstance(employees).As<IList<Employee>>();
autofac.RegisterInstance(Console.Out).As<TextWriter>();
using (var container = autofac.Build())
{
container.Resolve<EmployeeObserver>().FindExperts();
}
在其他一些Q &作为它表示我们可以在编写单元测试时看到autofac的优势。
除此之外,有人可以给出理由或细节更多为什么我应该使用autofac而不是手动依赖注入更复杂的代码?
它说:
可以在这个特殊的例子,很难看出为什么这种方法 比手工配置依赖注入更好,但你 应该注意一个重要的事情 - 与Autofac每个组件 独立于所有其他配置,这就是当你的应用程序变得更加复杂时, 会有什么不同。
你能指出一个这种情况的复杂版本的例子,它显示了我将坚持使用autofac用法vs依赖的优势吗?
相关:https://stackoverflow.com/questions/32032771/using-dependency-injection-without-any-di-framework – Steven
你确定其他地方谈论在单元测试中使用_autofac_,或者只是_dependency injection_在单元测试?您是否具体询问单元测试部分,或者一般情况下的DI/autofac?这是一个相当广泛的主题,所以要在这里回答你需要对你的问题做出相当准确的判断。 –
@JamesThorpe尤其不是单元测试部分,而是后者 –