如何在不使用mvc3中的构造函数模式的情况下从ninject获取资源
当将 Ninject 与 mvc3 一起使用时,我们会执行以下操作:安装 ninject、注册器模块或服务。
我们像这样编写控件
public class HomeController : Controller
{
private IHelloService _service;
public HomeController(IHelloService service)
{
_service = service;
}
public string Index()
{
return _service.GetGreeting();
}
}
我想做类似的事情
public class HomeController : Controller
{
private IHelloService _service;
/*
No default constructor
*/
public string Index()
{
_service= Ask_Ninject_to_provide_resource
return _service.GetGreeting();
}
}
When using Ninject with mvc3 we do something like, install ninject, registerger modules-or-services .
We write control like this
public class HomeController : Controller
{
private IHelloService _service;
public HomeController(IHelloService service)
{
_service = service;
}
public string Index()
{
return _service.GetGreeting();
}
}
I want to do something like
public class HomeController : Controller
{
private IHelloService _service;
/*
No default constructor
*/
public string Index()
{
_service= Ask_Ninject_to_provide_resource
return _service.GetGreeting();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您当前编写控件的做法比您建议的要好。您希望能够通过字段而不是构造函数注入。这是一个坏主意,不建议这样做。
引自 Ninject wiki:
“尽管它的简单性很诱人,但您通常应该尽量避免使用字段注入,因为只能通过 Ninject 设置该值,这使得单元测试变得更加复杂,因为有时手动使用依赖注入将模拟对象注入到单元测试中是最简单的(更多内容介绍了使用 Ninject 进行单元测试)。深度稍后。”
另一种方法是通过属性注入,但同样,您必须有一个很好的理由这样做。大多数时候,构造函数注入应该可以完成这项工作。
Your current practice of writing controls is better than what you are proposing. You want to be able to inject through fields, rather than constructor. This is a bad idea and it's not recommended.
Quote from Ninject wiki:
"Although its simplicity is tempting, you should generally try to avoid using field injection, since the value can then only be set via Ninject. This makes unit testing much more complex, since sometimes it's easiest to use dependency injection by hand to inject mock objects into your unit tests. (Unit testing with Ninject is covered in more depth later.)"
Alternative is to inject through properties, but once again, you have to have a very good reason to do so. Most of the time constructor injection should do the job.
尽管我会严重质疑这样做的必要性。
Though I would seriously question the need to do this.