2013-02-04 238 views
0

我有我经常使用的方法,以这样的依赖注入泛型类

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

返回结果有ILoggingService接口Result类日志服务注入,但我没有找到一个方法一般Result<T>通用类注入实际的实施。

我试着执行下面的代码,但是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 



     } 

回答

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; 
    } 
} 
+0

可ResolutionExtensions.Get帮助我在这种情况下?我在任何地方都找不到有关ResolutionExtensions中的方法的说明。 – Tomas

+0

+1 @Tomas阅读并相信答案 - Remo在他的建议中是正确的。你引用的方法最好被认为是相当于'Kernel.Get()' –