Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

.net - NLog: Dependency Injection for custom Targets

I am a user of NLog and I am creating my own custom target. This target will use some repositories (using NHibernate) to persist log entries.

Is it possible to inject the required constructor dependencies of custom targets using any IoC framework, preferably StructureMap?

Regards,

J

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I want to provide some context for people, since I was confused at first by your answer 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;
    }
}

This shows how you set up the instance creation and how it all fits together with NLog. Hope that helps other people!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...