C# ASP.NET MVC 6依赖项注入

C# ASP.NET MVC 6依赖项注入,c#,asp.net,asp.net-mvc,dependency-injection,C#,Asp.net,Asp.net Mvc,Dependency Injection,我有密码 public class VendorManagementController : Controller { private readonly IVendorRespository _vendorRespository; public VendorManagementController() { _vendorRespository = new VendorRespository(); } 现在我想使用依赖注入。因此,代码将是 pub

我有密码

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
对象的位置,以及如何使用定义的参数化
VendorRespository vendorRespositor)将其传递给
VendorManagementController
constructor?

在MVC6中,依赖项注入是框架的一部分,所以您不需要单元、Ninject等


这里有一个教程:

依赖项注入被烘焙到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
    }
public void配置服务(IServiceCollection服务)
{
//这里还有其他代码
//当前作用域中的单个实例。为此创建CoordService的副本
//范围,然后始终返回该实例
services.addScope();
//创建每次请求SingleUseClass时创建的新实例
services.AddTransient();
#如果调试
//在调试模式下,解析对IMailService的调用以返回DebugMailService
services.addScope();
#否则
//不调试时,请解析对IMailService的调用以返回
//实际的邮件服务,而不是调试版本
services.addScope();
#恩迪夫
}
该示例代码显示了以下几点:

  • 您注入的项的生命周期可以通过AddInstance、AddTransient、AddSingleton和AddScope进行控制
  • 编译时
    #if
    可用于在调试时和运行时注入不同的对象

中有更多信息,也是一个很好的工具。

您使用的是哪个DI容器?@IMU,我没有使用任何DI容器。我应该吗?是的,例如你可以使用StructureMap,这是如何使用的文档和示例,@IMU DI内置于MVC6中,你不需要单独的DI包酷,我没有尝试MVC6。谢谢,我刚找到Startup.cs
public void ConfigureServices(IServiceCollection services){services.AddMvc();}
,但我不知道如何放在那里。你看过演示了吗?我的代码是
services.AddTransient()。是吗?我想你需要做
服务。AddTransient()
。不过,这样每次都会创建一个新实例,您最好使用AddScope为当前范围创建一个repo实例,甚至使用AddSingleton在整个应用程序中创建一个实例。请参阅此处的更多信息: