问题描述
AutoFac如何比Microsoft.Extensions.DependencyInjection更好? Autofac支持属性和方法注入(但是我不太了解属性和方法注入在哪里有用)。
我的意思是,当Microsoft.Extensions.DependencyInjection可以做同样的事情时,为什么我应该使用AutoFac
解决方法
这是一个公平的问题;从根本上说,区别在于Autofac可以根据需要提供其他功能。对于简单的应用程序,Microsoft DI可能提供了足够的功能,但是我发现随着应用程序的增长,我发现自己需要/需要一些额外的功能。
在我看来,鼓励我最初开始使用Aufofac的功能是:
- 标记的生命周期范围和对这些标记的范围服务(https://autofaccn.readthedocs.io/en/latest/lifetime/instance-scope.html#instance-per-matching-lifetime-scope)
- 使用某些关联的元数据(https://autofaccn.readthedocs.io/en/latest/advanced/metadata.html)解决服务
- 定义服务的命名/键控变体(https://autofaccn.readthedocs.io/en/latest/advanced/keyed-services.html)
- 解决您可以随时使用的工厂功能(https://autofaccn.readthedocs.io/en/latest/resolve/relationships.html#dynamic-instantiation-func-b)
- 惰性实例化(https://autofaccn.readthedocs.io/en/latest/resolve/relationships.html#delayed-instantiation-lazy-b)
- 可以随意组合所有这些功能(例如
Meta<Lazy<IMyService>>
)
还有更多功能,但这是我最喜欢的功能。检查文档的所有好处。
此外,没有理由您无法开始使用内置DI,然后在意识到需要时再添加Autofac。 Autofac ASP.NET Core集成(https://autofaccn.readthedocs.io/en/latest/integration/aspnetcore.html)只会获取您所有的现有注册,然后您可以在顶部添加这些额外的功能。
为了在此处进行全面披露,我将指出我是Autofac的维护者之一。