我有代码,
public class VendorManagementController : Controller
{
private readonly IVendorRespository _vendorRespository;
public VendorManagementController()
{
_vendorRespository = new VendorRespository();
}
现在我想使用依赖注入。所以代码将是
public class VendorManagementController : Controller
{
private readonly IVendorRespository _vendorRespository;
public VendorManagementController(IVendorRespository vendorRespositor)
{
_vendorRespository = vendorRespositor;
}
我的问题是我找不到可以创建VendorRespository
对象的位置以及如何将其传递给定义参数化VendorManagementController
构造函数的VendorManagementController(IVendorRespository vendorRespositor)
?
答案 0 :(得分:3)
在MVC6中,依赖注入是框架的一部分 - 所以你不需要Unit,Ninject等。
这是一个教程:http://dotnetliberty.com/index.php/2015/10/15/asp-net-5-mvc6-dependency-injection-in-6-steps/
答案 1 :(得分:1)
依赖注入被纳入ASP.NET MVC 6.要使用它,您只需要在Startup.cs的ConfigureServices方法中设置依赖项。
代码如下所示:
public void ConfigureServices(IServiceCollection services)
{
// Other code here
// Single instance in the current scope. Create a copy of CoordService for this
// scope and then always return that instance
services.AddScoped<CoordService>();
// Create a new instance created every time the SingleUseClass is requested
services.AddTransient<SingleUseClass>();
#if DEBUG
// In debug mode resolve a call to IMailService to return DebugMailService
services.AddScoped<IMailService, DebugMailService>();
#else
// When not debugging resolve a call to IMailService to return the
// actual MailService rather than the debug version
services.AddScoped<IMailService, MailService>();
#endif
}
该示例代码显示了一些内容:
#if
可用于在调试时和运行时注入不同的对象。official documentation for ASP.NET MVC 6 Dependency Injection中有更多信息,还有一个好basic walk-through here。