c# - 如何在我自己的类中注入 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”相对应的参数
如何为此创建实例。
解决方案
问题在以下行:
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>();
}
推荐阅读
- loops - 我的总数没有加起来,而是保持为 0
- c# - 在 Http 响应消息中查找 POST 的结果
- ios - (空)协议一致性测试
- javascript - p5.js Prim 的算法迷宫生成:陷入无限循环
- marklogic-9 - MarkLogic - JSON 文档的 mlcp 导出
- ionic-framework - 将默认日期添加到 ionic-datetime - ionic 4 angular 项目
- javascript - 使用 Jasonette 在 Android 中调用 Javascript 函数
- c++ - 出于对象替换的目的,对象的“名称”究竟是什么?
- visual-studio-code - 如何配置vscode的lanuch.json文件运行debug时自动更新模块
- ruby-on-rails - 在 ruby 模型中使用自定义方法过滤数据