我有泛型Result<T>
泛型类,我经常在方法中使用它来返回像这样的结果
public Result<User> ValidateUser(string email, string password)
ILoggingService
类中有Result
接口用于记录服务注入,但我找不到注入实际实现的方法。
我尝试执行下面的代码,但TestLoggingService
intance未注入LoggingService
属性。它总是返回null。任何想法如何解决?
using (var kernel = new StandardKernel())
{
kernel.Bind<ILoggingService>().To<TestLoggingService>();
var resultClass = new ResultClass();
var exception = new Exception("Test exception");
var testResult = new Result<ResultClass>(exception, "Testing exception", true);
}
public class Result<T>
{
[Inject]
public ILoggingService LoggingService{ private get; set; } //Always get null
protected T result = default(T);
//Code skipped
private void WriteToLog(string messageToLog, object resultToLog, Exception exceptionToLog)
{
LoggingService.Log(....); //Exception here, reference is null
}
答案 0 :(得分:2)
您正在使用new
手动创建实例。 Ninject只会注入由kernel.Get()
创建的对象。此外,您似乎尝试将某些东西注入到不推荐的DTO中。最好在创建结果的类中进行日志记录:
public class MyService
{
public MyService(ILoggingService loggingService) { ... }
public Result<T> CalculateResult<T>()
{
Result<T> result = ...
_loggingService.Log( ... );
return result;
}
}