问题描述
ioc和依赖注入之间的区别。在春季解释依赖注入。 b / w JSF依赖项注入和spring依赖项注入有什么区别。
Difference between ioc and dependency injection . explain dependency injection in spring. What is difference b/w JSF dependency injection and spring dependency injection..
推荐答案
IoC意味着控制反转。
IoC means Inversion of Control.
让我们看一些强耦合的代码( MyComponent取决于 Logger):
Let’s see some "strongly coupled code" ("MyComponent" depends on "Logger"):
public class MyComponent
{
public MyComponent()
{
:
}
public void DoSomeWork()
{
var logger = new Logger();
:
}
}
我们可以将其更改为使用一个接口,但必须提供实现:
We can change it to use an "interface", but someone must provide the "implementation":
public class MyComponent
{
public MyComponent()
{
:
}
public void DoSomeWork()
{
ILogger logger = ...; // who’s going to provide this?
:
}
}
依赖注入(DI)为IoC的特定实现。
Dependency Injection (DI) is a specific implementation of IoC.
//Dependency Injection pattern
public class MyComponent
{
private ILogger _logger;
public MyComponent(ILogger logger)
{
_logger = logger;
}
public void DoSomeWork()
{
// Use the logger component here
_logger.Log();
:
}
}
另一种实现是Service Locator。
Another implementation is Service Locator.
//Service Locator pattern
public class MyComponent
{
public MyComponent()
{
:
}
public void DoSomeWork()
{
ILogger logger = ServiceLocator.GetService();
:
}
}
马丁·福勒(Martin Fowler)说:服务定位器,应用程序类通过给定位器的消息显式地请求它。对于注入,没有显式请求,该服务将出现在应用程序类中,因此会导致控件反转。
Martin Fowler states: "With service locator the application class asks for it explicitly by a message to the locator. With injection there is no explicit request, the service appears in the application class – hence the inversion of control."
另外:在服务定位器和依赖注入之间的选择是不如将应用程序中的服务配置与服务使用分离的原理重要。
Also : "The choice between Service Locator and Dependency Injection is less important than the principle of separating service configuration from the use of services within an application. "
您可以查看该帖子:
也:
,由Dino Esposito
ASP.NET MVC: Resolve or Inject? That’s the Issue… by Dino Esposito
a>马丁·福勒(Martin Fowler)
InversionOfControl by Martin Fowler
这篇关于IOC和依赖注入之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!