我有下面的代码来创建日志文件。
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”相对应的参数
如何为此创建实例。
答案 0 :(得分:2)
问题在以下行:
<script>
$('#newSpScenarioId').on('click', function() {
document.getElementById('scenarioFormForAction:createNewScenarioSp').click();
});
</script>
<script>
function afterCompleteLoadTree() {
alert("ROW CREATED IN DB !!!");
$('#spModOutput').fadeOut(100);
$('#spModOutput').fadeIn(100);
$('#spModOutput').jqxTree("refresh");
}
</script>
<h:form id="scenarioFormForAction">
//put tree in a form
<a4j:outputPanel id="msg"> //use outputPanel
<div id="spModOutput">
<ui:repeat value="#{ActionClass.listMethod()}" var="scenarioVar">
"#{scenarioVar.scenarioId}"
</ui:repeat>
</div>
</a4j:outputPanel>
<a4j:commandLink id="createNewScenarioSp" style="visibility: hidden;"
action="#{ActionClass.createNewRow()}"
oncomplete="afterCompleteLoadTree()"
reRender="msg"> //use reRender attr
</a4j:commandLink>
</h:form>
在创建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
答案 1 :(得分:1)
.NET Core
中的DependencyInjection要求您注册类及其依赖项,以便它可以在创建类实例之前创建/检索任何依赖项。
根据您的评论,我假设您尚未在服务集合中注册LoggingService
,并且您正在尝试在控制器中创建实例。
首先,您需要在startup.cs中向LoggingService
注册IServiceCollection
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<LoggingService>();
services.AddMvc();
}
这告诉DI服务,当类在其构造函数中要求LoggingService
时,它必须创建该类的实例。幕后.NET Core
已经在DI服务中注册了IHostingEnvironment
界面,因此我们不必为此担心。当DI服务必须创建我们的LoggingService
实例时,它将自动注入IHostingEnvironment
依赖项。
现在我们需要将类注入到我们的控制器中:
public class ValuesController : Controller
{
private readonly LoggingService _loggingService;
public ValuesController(LoggingService loggingService)
{
_loggingService = loggingService;
}
...
}
当.NET Core
创建我们的ValuesController
的实例时,它将看到它是否知道如何创建LoggingService
的实例-这样做是因为我们在{{ 1}}。
关于依赖项注入要记住的一件事,您几乎总是从不使用startup.cs
创建一个类。 (对此有一些例外,但是您应该始终尝试让DI服务创建类而不需要使用new
关键字。)
我建议您花一些时间阅读documentation on Dependency Injection,以便您完全了解new
中的依赖项注入如何工作以及可用的不同范围。