我们已经开始使用Ninject版本2作为我们的IoC容器以及通过命名约定解析的扩展.我们还使用log4net进行日志记录.
我想要的是让Ninject记录它找到的所有依赖项以及将它们解决的依赖项,最好是在应用程序启动时.
我找到了日志记录扩展,但找不到有关如何使用它来获取此文档或示例.
编辑:
因为这里请求的是使用log4net在启动时记录默认绑定的类
public class DefaultBindingGeneratorWithLogging:IBindingGenerator
{
private readonly IKernel kernel;
/// <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",interfaceForType.FullName); } } }@H_403_16@
解决方法
你可以通过创建自己的’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; }
希望这可以帮助.
短发
@H_403_16@ @H_403_16@ 原文链接:https://www.f2er.com/csharp/96556.html