ASP.Net DI使用控制器中的类而不在该控制器中实例化该类

时间:2017-07-26 16:45:18

标签: dependency-injection asp.net-core

我有“appsettings.json”文件内容

{
 "Logging": {
 "IncludeScopes": false,
 "LogLevel": {
 "Default": "Debug",
 "System": "Information",
 "Microsoft": "Information"
 }
},
 "appData": {
 "applicationDeveloper": "El Bayames"
 }
}

一个从appsettings读取的课程

public class learningDIGlobalVariables
{
    private String _applicationDeveloper;
    private String _webRootFolderPath;

    public String applicationDeveloper
    {
        get
        {
            return _applicationDeveloper;
        }
    }
    public String webRootFolderPath
    {
        get
        {
            return _webRootFolderPath;
        }
    }

    public learningDIGlobalVariables(IConfigurationRoot auxConfRoot, Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnvironment)
    {
        _applicationDeveloper = auxConfRoot["appData:applicationDeveloper"];
        _webRootFolderPath = hostingEnvironment.WebRootPath;
    }
}

在设置容器中我有

    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();
        services.AddSingleton<IConfigurationRoot>(Configuration);
    }

在控制器中我有

public class HomeController : Controller
{
    private learningDIGlobalVariables _learningDIGlobalVariables;
    public HomeController(IConfigurationRoot auxConfRoot, Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnvironment)
    {
        _learningDIGlobalVariables = new learningDIGlobalVariables(auxConfRoot, hostingEnvironment);
    }
}

如何在控制器中使用该类“learningDIGlobalVariables”而不实例化它?该类是否不会被框架实例化?如果我必须将该类添加到服务中,我该如何操作并在后面使用它?

2 个答案:

答案 0 :(得分:0)

如果您不想实例化calss而不是将其设置为静态,请删除构造函数并添加SetGlobals方法:

public class learningDIGlobalVariables
{
    public static SetGlobals(IConfigurationRoot auxConfRoot, Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnvironment)
    {
        _applicationDeveloper = auxConfRoot["appData:applicationDeveloper"];
        _webRootFolderPath = hostingEnvironment.WebRootPath;
    }
}

在你的启动中,你可以在Configure函数中设置全局变量:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // Add framework services.
    services.AddMvc();
    services.AddSingleton<IConfigurationRoot>(Configuration);
    learningDIGlobalVariables.SetGlobals(app.ApplicationServices.GetService<IConfigurationRoot>(), env);
}

答案 1 :(得分:0)

创建一个简单的POCO来表示您的JSON配置。

public class AppSetting
{
  public AppData AppData {set;get;}
}
public class AppData
{
   public string ApplicationDeveloper { set;get;}
}

现在在Startup.cs类ConfigureServices方法中。

services.Configure<AppSettings>(Configuration);

现在在您的控制器中,您将使用构造函数注入。你不需要在这里新建任何对象。该框架将为您注入依赖。

public class HomeController : Controller
{
    private IOptions<AppSetting> _settings;

    public HomeController(IOptions<AppSetting> settings)
    {
        this._settings= settings;
    }
}

在控制器内部,您可以使用this._settings.Value.AppData.ApplicationDeveloper获取您在json中设置的值。