NLog: Injecting dependencies for custom purposes

I am an NLog user and I create my own custom goal. This target will use some repositories (using NHibernate) to save log entries.

Is it possible to introduce the required constructor dependencies on custom targets using any IoC structure, preferably StructureMap?

Hi,

J

+3
source share
2 answers

The author of the toolkit updated the framework to expose hooks for using its own DI container. The following is one possible use:

   public class LoggingConfiguration : ILoggingConfiguration
{
    public void SetDependencyResolver(IContainer container)
    {
        ConfigurationItemFactory.Default.CreateInstance = (Type type) => container.GetInstance(type);
    }
}

public static class DiagnosticsConfiguration
{
    public static void Configure(Action<ILoggingConfiguration> configuration)
    {
        var config = new LoggingConfiguration();
        configuration(config);
    }
}

public interface ILoggingConfiguration
{
    void SetDependencyResolver(IContainer container);
}

public interface IContainer
{
    object GetInstance(Type type);
}

public class StructureMapDependencyFactory : IContainer
{
    public object GetInstance(Type type)
    {
        return ObjectFactory.GetInstance(type);
    }

    public T GetInstance<T>()
    {
        return ObjectFactory.GetInstance<T>();
    }
}

Hope this helps someone.

J

+2
source

, JC.

public Program {

    //
    // Static constructor
    //
  static Program() {
    // Set up Ninject
    var kernel = new StandardKernel();

    // Register bindings
    RegisterServices(kernel);

    // Set up Ninject logging config
    NLog.Config.ConfigurationItemFactory.Default.CreateInstance = 
        (type) => kernel.TryGet(type);

    // Continue on!
  }

  private static void RegisterServices(IKernel kernel) {
    // bind services!
    kernel.Bind<IMyClass>().To<MyClass>();
  }
}

[Target("Custom")]
public class CustomTarget : TargetWithLayout {

    private IMyClass _myClass;
    public CustomTarget(IMyClass myClass) {

        // This will be injected!
        _myClass = myClass;
    }
}

, NLog. , !

+8

All Articles