ASP.NET 5 DI 应用程序在控制器外部设置

Mic*_*Mao 5 asp.net asp.net-mvc asp.net5

我可以像这样在控制器中进行 DI 应用程序设置

 private IOptions<AppSettings> appSettings;
 public CompanyInfoController(IOptions<AppSettings> appSettings)
 {
     this.appSettings = appSettings;
 }
Run Code Online (Sandbox Code Playgroud)

但是如何在我的自定义类中像这样进行 DI

  private IOptions<AppSettings> appSettings;
  public PermissionFactory(IOptions<AppSettings> appSetting)
  {
      this.appSettings = appSettings;
  }
Run Code Online (Sandbox Code Playgroud)

我在 Startup.cs 中的寄存器是

services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
Run Code Online (Sandbox Code Playgroud)

qbi*_*bik 4

“正确”的方式

在 DI 中注册自定义类,就像在ConfigureServices方法中注册其他依赖项一样,例如:

services.AddTransient<PermissionFactory>();
Run Code Online (Sandbox Code Playgroud)

AddTransient(您可以使用AddScoped或您需要的任何其他生命周期来代替)

然后将此依赖项添加到控制器的构造函数中:

public CompanyInfoController(IOptions<AppSettings> appSettings, PermissionFactory permFact)
Run Code Online (Sandbox Code Playgroud)

现在,DI 知道PermissionFactory,可以实例化它并将其注入到您的控制器中。

PermissionFactory如果你想在方法中使用Configure,只需将其添加到其参数列表中即可:

Configure(IApplicationBuilder app, PermissionFactory prov)
Run Code Online (Sandbox Code Playgroud)

Aspnet 将发挥它的魔力并将类注入其中。

“恶心”的方式

如果你想PermissionFactory在代码深处实例化,你也可以用一种有点讨厌的方式来实现——在IServiceProvider类中存储引用Startup

internal static IServiceProvider ServiceProvider { get;set; }

Configure(IApplicationBuilder app, IServiceProvider prov) {
   ServiceProvider = prov;
   ...
}
Run Code Online (Sandbox Code Playgroud)

现在您可以像这样访问它:

var factory = Startup.ServiceProvider.GetService<PermissionFactory>();
Run Code Online (Sandbox Code Playgroud)

同样,DI 将负责注入IOptions<AppSettings>PermissionFactory.

Asp.Net 依赖注入中的 5 个文档