0

我有通用的Result<T>泛型类,我经常在方法中使用它来返回这样的结果

public Result<User> ValidateUser(string email, string password)

类中有用于记录服务注入的ILoggingService接口,Result但我找不到注入实际实现的方法。

我试图执行下面的代码,但TestLoggingService实例没有注入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



        }
4

1 回答 1

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;
    }
}
于 2013-02-04T17:22:30.040 回答