将Windsor Logging Facility安装到库中

时间:2011-12-01 11:59:52

标签: c# logging dependency-injection inversion-of-control castle-windsor

我正在开发一个框架,我在其中进行了大量的日志记录。我通过这种属性模式使用Castle Windsor的ILogger:

namespace Framework
{
    public class SomeClass
    {
        private ILogger _logger = NullLogger.Instance;
        public ILogger Logger
        {
            get { return _logger; }
            set { _logger = value; }
        }

        public void DoSomething()
        {
            Logger.Info("Doing something.");
        }

        //...

    }
}

我还在框架内提供了一个安装程序:

namespace MyFramework
{
    public class LoggerInstaller : IWindsorInstaller
    {
        private readonly string _configPath;

        public LoggerInstaller(string configPath)
        {
            _configPath = configPath;
        }

        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.AddFacility("logging", new LoggingFacility(LoggerImplementation.Log4net, _configPath));
            //I've also tried this one:
            //container.AddFacility<LoggingFacility>(f => f.LogUsing(LoggerImplementation.Log4net).WithConfig(_configPath));
        }
    }
}

然后从其他项目引用该项目。例如,在测试项目中,我将首先安装记录器来构建测试。我用一个抽象类来做这个,我所有长时间运行的测试都扩展了:

namespace Framework.Test
{
    public abstract class Log4NetLoggedTest
    {
        private const string ConfigFilePath = "log4net.config";
        protected ILogger Logger { get; set; }
        protected IWindsorContainer Container { get; set; }

        protected Log4NetLoggedTest()
        {
            Container = new WindsorContainer();

            Container.Install(new LoggerInstaller(ConfigFilePath));

            Logger = Container.Resolve<ILogger>();
        }

        ~Log4NetLoggedTest()
        {
            Container.Dispose();
        }
    }
}

所以我的测试看起来像这样:

namespace Framework.Test
{
    [TestFixture]
    public class MyLongRunningTest : Log4NetLoggedTest
    {
        [Test]
        [Category("LongRunning")]
        public void ModelConvergesForS50()
        {
            Logger.Info("Starting test...");

            var obj = new SomeClass();
            obj.DoSomething();

            // ...
        }
    }
}

测试的ILogger Logger得到解决并正确设置,所以在这个例子中我得到了“Starting test ...”而不是“做某事”。 SomeClass的ILogger保留为NullLogger。

请帮忙!

2 个答案:

答案 0 :(得分:2)

您使用'new'实例化SomeObj而不是通过容器。如果您没有通过容器,则无法注入依赖项

答案 1 :(得分:0)

我可能会说些蠢事,但是,不应该是这样的:

namespace Framework.Test
{
    [TestFixture]
    public class MyLongRunningTest : Log4NetLoggedTest
    {
        [Test]
        [Category("LongRunning")]
        public void ModelConvergesForS50()
        {
            Logger.Info("Starting test...");

            var obj = new SomeClass();
            obj.Logger = Logger;
            obj.DoSomething();

            // ...
        }
    }
}

我看不到你在任何地方应用你在类中使用的记录器实例。