ASP.NET MVC 6 依赖注入

本文关键字:依赖 注入 MVC NET ASP | 更新日期: 2023-09-27 18:32:08

我有代码,

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

ASP.NET MVC 6 依赖注入

在MVC6中,依赖注入是框架的一部分 - 所以你不需要Unit,Ninject等。

这是一个教程:http://dotnetliberty.com/index.php/2015/10/15/asp-net-5-mvc6-dependency-injection-in-6-steps/

依赖注入被烘焙到 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
    }

该示例代码显示了一些内容:

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

MVC 6 依赖项注入的官方文档中提供了更多信息 ASP.NET 此处也是一个很好的基本演练。