NLog: Dependency Injection for custom Targets

后端 未结 2 1459
情深已故
情深已故 2021-01-18 21:08

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 inje

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-18 21:26

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

       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 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()
        {
            return ObjectFactory.GetInstance();
        }
    }
    

    Hopefully this will help out someone.

    J

提交回复
热议问题