RazorEngine TemplateServiceConfiguration与log4net LogicalThreadStack

时间:2018-01-11 20:06:45

标签: c# unit-testing log4net razorengine

由于xUnit并行执行多个线程,因此必须使用log4net中的LogicalThreadContext来仅检索与当前测试相关的消息(欢迎使用其他方法的任何想法)。

通常我对这个设置没有问题但是。今天我改变了一个使用RazorEngine的测试也使用下面的解决方案(在我用线程名称过滤ID之前)。它不再起作用了。测试显示问题在于TemplateServiceConfiguration的实例化。

有谁知道发生了什么事?

通常这有效:

    var mapp = new MemoryAppender();
    BasicConfigurator.Configure(mapp);

    ILog logger = LogManager.GetLogger("moduleX");
    using (log4net.LogicalThreadContext.Stacks["TestStack"].Push("context"))
    {
        logger.Warn("Something happened!");

        mapp.GetEvents().Where(x => (string)x.Properties["TestStack"] == "context").ToList().Count.ShouldBe(1);
    }

但是,一旦我引入了TemplateServiceConfiguration,它就不会:

    var mapp = new MemoryAppender();
    BasicConfigurator.Configure(mapp);

    ILog logger = LogManager.GetLogger("moduleX");
    using (log4net.LogicalThreadContext.Stacks["TestStack"].Push("context"))
    {
        logger.Warn("Something happened!");

        var tsc = new TemplateServiceConfiguration();

        logger.Warn("More happenings!");

        // assert now fails
        mapp.GetEvents().Where(x => (string)x.Properties["TestStack"] == "context").ToList().Count.ShouldBe(2);
    }

更新

事件仍然存在,但Properties属性不再包含TestStack条目。

结束更新

以下是TemplateServiceConfiguration

的构造函数代码
    [SecuritySafeCritical]
    public TemplateServiceConfiguration()
    {
        Activator = new DefaultActivator();
        CompilerServiceFactory =
    #if RAZOR4
          new Roslyn.RoslynCompilerServiceFactory();
    #else
            new DefaultCompilerServiceFactory();
    #endif
        EncodedStringFactory = new HtmlEncodedStringFactory();

    #if !RAZOR4
    #pragma warning disable 0618 // Backwards Compat.
        CodeInspectors = new List<ICodeInspector>();
    #pragma warning restore 0618 // Backwards Compat.
    #endif

        ReferenceResolver = new UseCurrentAssembliesReferenceResolver();
        CachingProvider = new DefaultCachingProvider();
        TemplateManager =
            new DelegateTemplateManager();

        Namespaces = new HashSet<string>
                         {
                             "System", 
                             "System.Collections.Generic", 
                             "System.Linq"
                         };

        var config = RazorEngineConfigurationSection.GetConfiguration();
        Language = (config == null)
                       ? Language.CSharp
                       : config.DefaultLanguage;
    }

0 个答案:

没有答案