2011-01-13 35 views
6

我們已經開始使用Ninject版本2作爲我們的Io​​C容器以及用於通過命名約定來解決的擴展。我們也在使用log4net進行日誌記錄。日誌ninject已解決的依賴關係應用程序啓動

我想讓Ninject記錄它找到的所有依賴關係以及解決它們的方法,最好是在應用程序啓動時。

我找到了日誌擴展,但找不到文檔或示例如何使用它來獲取此信息。

編輯:

既然在這裏要求的是,登錄時啓動缺省綁定,使用log4net的

公共類DefaultBindingGeneratorWithLogging類:IBindingGenerator { 私人只讀的iKernel內核;

/// <summary> 
    /// Initializes a new instance of the <see cref="DefaultBindingGeneratorWithLogging"/> class. 
    /// </summary> 
    /// <param name="kernel">The kernel.</param> 
    public DefaultBindingGeneratorWithLogging(IKernel kernel) 
    { 
     this.kernel = kernel; 
    } 

    /// <summary> 
    /// Creates the bindings for a type. 
    /// </summary> 
    /// <param name="type">The type for which the bindings are created.</param> 
    /// <param name="bindingRoot">The binding root that is used to create the bindings.</param> 
    /// <returns> 
    /// The syntaxes for the created bindings to configure more options. 
    /// </returns> 
    public IEnumerable<IBindingWhenInNamedWithOrOnSyntax<object>> CreateBindings(Type type, IBindingRoot bindingRoot) 
    { 
     if (type.IsInterface || type.IsAbstract) 
     { 
      yield break; 
     } 

     Type interfaceForType = type.GetInterface("I" + type.Name, false); 
     if (interfaceForType == null) 
     { 
      yield break; 
     } 

     var log = kernel.Get<ILog>(); 
     if (!(kernel.GetBindings(interfaceForType).Any())) 
     { 
      bindingRoot.Bind(interfaceForType).To(type).InTransientScope(); 
      if (log.IsInfoEnabled && !String.IsNullOrWhiteSpace(interfaceForType.FullName)) 
      { 
       log.InfoFormat("Mapping {0} -> {1}", type.FullName, interfaceForType.FullName); 
      } 
     } 
     else 
     {     
      log.InfoFormat("Didn't map {0} -> {1} mapping already exists", type.FullName, interfaceForType.FullName); 
     } 
    } 
} 

回答

13

您可以通過創建自己的'ActivationStrategy'實例來實現您正在嘗試做的事情。這裏是我用來監視激活/去激活的一個:

public class MyMonitorActivationStrategy : ActivationStrategy 
{ 
    private ILogger _logger; 

    public override void Activate(Ninject.Activation.IContext context, Ninject.Activation.InstanceReference reference) 
    { 
     if(reference.Instance is ILogger) 
     { 
      _logger = (ILogger)reference.Instance; 
     } 
     _logger.Debug("Ninject Activate: " + reference.Instance.GetType()); 
     base.Activate(context, reference); 
    } 

    public override void Deactivate(Ninject.Activation.IContext context, Ninject.Activation.InstanceReference reference) 
    { 
     _logger.Debug("Ninject DeActivate: " + reference.Instance.GetType()); 
     base.Deactivate(context, reference); 
    } 
} 

當你創建你的內核時,你需要連接它。

protected override IKernel CreateKernel() 
    { 
    var kernel = new StandardKernel(); 
     kernel.Components.Add<IActivationStrategy, MyMonitorActivationStrategy>(); 

     kernel.Load<AppModule>(); 

     return kernel; 
    } 

希望這會有所幫助。

鮑勃

+0

注意:這將記錄綁定,當它們被激活/停用時。有點不同於在啓動時記錄它們,但可能有用嗎? – rcravens 2011-01-24 16:28:25