首页 > 解决方案 > 如何在我自己的类中注入 IHostingEnvironment

问题描述

我有下面的代码来创建一个日志文件。

public class LoggingService
{
    private readonly IHostingEnvironment env;

    public LoggingService(IHostingEnvironment env)
    {
            this.env = env;
    }

    public void WriteLog(string strLog)
    {
            //Some code is Here
    }
}

以下访问控制器函数中的类

LoggingService log =  new LoggingService();
log.WriteLog("Inside GetUserbyCredential function");

当我尝试从控制器类创建实例以将某些值传递给函数时。当时我收到以下错误

没有给出与“LoggingService.LoggingService(IHostingEnvironment)”所需的形式参数“env”相对应的参数

如何为此创建实例。

标签: c#asp.net-core.net-coreasp.net-core-mvc

解决方案


问题在以下行:

LoggingService log =  new LoggingService();

当您创建LoggingService类的实例时,您没有将其传递IHostingEnvironment给它的构造函数,这就是它变为空的原因。

为了克服这个问题,尝试如下:

public interface ILoggingService
{
   void WriteLog(string strLog);
}

public class LoggingService : ILoggingService
{

    private readonly IHostingEnvironment env;

    public LoggingService(IHostingEnvironment env)
    {
        this.env = env;
    }
    public void WriteLog(string strLog)
    {

        //Some code is Here
    }
}

然后在你的控制器中:

public class YourController : Controller
{
     private readonly ILoggingService _loggingService;
     public YourController(ILoggingService loggingService)
     {
         _loggingService = loggingService;
     }

     public IActionResult YourMethod()
     {
        _loggingService.WriteLog("Inside GetUserbyCredential function");
     }
}

最后在类的ConfigureServices方法中Startup如下:

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<ILoggingService, LoggingService>();
}

推荐阅读