after lots of efforts in DI i could finally figure out the basics,but as long as i know up to now,instantiating or using NEW key word in the controller means we are still not satisfying the DI,i have created a small project to point out my problem:
经过DI的努力,我终于可以找到基础知识,但只要我知道到目前为止,在控制器中实例化或使用NEW关键字意味着我们仍然不满足DI,我创建了一个小项目来指向我的问题:
public interface IOperations
{
int mul(int a, int b);
}
The implementation of my Interface:
我的界面的实现:
public class Operations:IOperations
{
public int mul(int a,int b){
return a * b;
}
}
In my controller i create my constructor :
在我的控制器中,我创建我的构造函数:
private IOperations _ioperations;
public HomeController(IOperations _ioperations)
{
this._ioperations = _ioperations;
}
Handler class:
public readonly IOperations _ioperation;
public Handeler(IOperations _ioperation)
{
this._ioperation = _ioperation;
}
Binding class:
public class Binding:NinjectModule
{
public override void Load()
{
Bind<IOperations>().To<Operations>();
}
}
}
and at the end my controller:
最后我的控制器:
var kernel = new StandardKernel();
kernel.Load(Assembly.GetExecutingAssembly());
var _operation = kernel.Get<IOperations>();
var handler = new Handeler(_operation);
var result=handler._ioperation.mul(5, 2);
i have copied these from a site which is how to work with Ninject,to me it looks very odd,in my controller if you see i am using "new" key word and instantiate which as far as i know we should not do that otherwise whats the point of DI?can anyone explain me?
我已经从一个如何使用Ninject的网站复制了这些,对我而言看起来很奇怪,如果你看到我正在使用“新”关键词并实例化,据我知道我们不应该这样做什么是DI的观点?谁能解释我?
1 个解决方案
#1
0
Instead on initializing in your controller, you should use the Application_Start() method in Global.asax file to register the bindings as then we'll not have to do the same for every controller. Refer this link for the complete implementation.
而不是在控制器中进行初始化,您应该使用Global.asax文件中的Application_Start()方法来注册绑定,因为我们不必为每个控制器执行相同的操作。请参阅此链接以获取完整实施。
#1
0
Instead on initializing in your controller, you should use the Application_Start() method in Global.asax file to register the bindings as then we'll not have to do the same for every controller. Refer this link for the complete implementation.
而不是在控制器中进行初始化,您应该使用Global.asax文件中的Application_Start()方法来注册绑定,因为我们不必为每个控制器执行相同的操作。请参阅此链接以获取完整实施。