我有密码,
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(IVendorRespository vendorRespositor)构造函数将其传递给VendorManagementController?
发布于 2016-01-26 15:38:54
在MVC6中,依赖项注入是框架的一部分--所以您不需要单元、尼尼微等等。
下面是一个教程:http://dotnetliberty.com/index.php/2015/10/15/asp-net-5-mvc6-dependency-injection-in-6-steps/
发布于 2016-01-26 15:56:47
依赖注入是在ASP.NET MVC 6中完成的。要使用它,只需要在ConfigureServices方法Startup.cs中设置您的依赖项。
代码如下所示:
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可用于在调试时和运行时注入不同的对象。在ASP.NET MVC 6依赖项注入的正式文档中有更多的信息,也是一个很好的基本通过这里。
https://stackoverflow.com/questions/35017519
复制相似问题