依赖注入初始化 [英] Dependency Injection Initialization

查看:203
本文介绍了依赖注入初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请注意:使用AutoFac了解DI和IOC我刚刚开始。

Please note: I have just started using AutoFac to learn about DI and IoC.

时的依赖注入应该在控制器构造函数初始化?

Is dependency injection supposed to be initialized in the controllers constructor?

这是怎么回事?

private IMyService iMyService;
public HomeController(IMyServices myService)
{
    iMyService = myService;
}

从不同...

public IMyService iMyService = new MyService();

最后,它看起来像依赖仍然存在。

Lastly, it seems like the dependency still exists.

编辑:修正了错字,则将MyService新();是新IMyService();

Fixed typo, new MyService(); was new IMyService();

推荐答案

依赖注入究竟意味着注射依赖。它没有说关于初始化什么。例如。如果你正在依赖注入是单身,那么就可以初始化你注入它很久以前。

Dependency Injection means exactly injection of dependency. It does not say anything about initialization. E.g. if you are injecting dependency which is Singleton, then it can be initialized long before you are injecting it.

您最初的code是通过构造通常依赖注入。你的第二个code不是依赖注入。其实这看起来很奇怪我 - 要么你要创建接口实例,这是不可能的,或者你在这里有坏的命名。如果它只是坏的命名或错字,那么第二个样本真的应该是这样的:

Your first code is a usual dependency injection via constructor. Your second code is not dependency injection. Actually it looks odd to me - either you are trying to create instance of interface, which is not possible, or you have bad naming here. If it is just bad naming or typo, then second sample should really look like:

 public IMyService iMyService = new MyServiceImplementation();

但你不在这里注入任何东西。您只需创建的依赖实例(这使得连接到的依赖实现控制器)。

But you are not injecting anything here. You are simply creating dependency instance (which makes your controller coupled to dependency implementation).

这篇关于依赖注入初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆