Castle Windsor不会在物业中注入Logger!简单的例子

时间:2011-05-19 06:54:25

标签: c# inversion-of-control log4net castle-windsor

  

可能重复:
  Castle Windsor won't inject Logger in a property!

我写了一篇类似的帖子(Castle Windsor won't inject Logger in a property!),但没有人能提供解决方案,所以我在这里准备了一个简单的完整代码示例:

using Castle.Core.Logging;
using Castle.Facilities.Logging;
using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;

namespace IocTest
{


public class LoggerInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
         container.AddFacility("logger", new LoggingFacility(LoggerImplementation.Log4net, "log4net.config"));
    }
}
public class LogicInstaller : IWindsorInstaller
{
     public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(AllTypes.FromThisAssembly()
                            .Pick()
                            .If(t => t.Name.StartsWith("Logic"))
                            .Configure((c => c.LifeStyle.Transient)));
    }
}

class Program
{
    static void Main(string[] args)
    {
        IWindsorContainer container = new WindsorContainer();

        container.Install(
        new LoggerInstaller(),
          new LogicInstaller()
          );


        LogicClass1 logic1 = container.Resolve<LogicClass1>();
        LogicClass2 logic2 = container.Resolve<LogicClass2>();
    }
}

public class LogicClass1
{
    private ILogger logger = NullLogger.Instance;
    public ILogger Logger
    {
        get { return logger; }
        set { logger = value; }
    }

    public LogicClass1()
    {
        logger.Debug("Here logger is NullLogger!");
    }
}

public class LogicClass2
{
    public LogicClass2(ILogger logger)
    {
        logger.Debug("Here logger is properly injected!");
    }
}
}

出了什么问题?

0 个答案:

没有答案