Where & How Castle Windsor sets up logging facility

青春壹個敷衍的年華 提交于 2019-11-30 04:09:33

The logger is setup by the logging facility, which is in the <facilities> section of the configuration. For example to use log4net your app or web.config would look something like this:

<?xml version="1.0"?>
<configuration>
    <configSections>
        <section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor"/>
    </configSections>
<Configuration>

<castle>

    <facilities>
        <facility id="loggingfacility" 
             type="Castle.Facilities.Logging.LoggingFacility, Castle.Facilities.Logging" 
             loggingApi="log4net" 
             configFile="logging.config" />
    </facilities>

</castle>
</configuration>

You can also configure this programatically when you initialise windsor (e.g. from your global.asax.cs):

container.AddFacility("logging",  new LoggingFacility(LoggerImplementation.Log4net));

You can of course choose any of the logger implimentations.

This this will be wired up whenever windsor instantiates any class expecting a logger. I wouldn't put this in the constructor as it's a cross cutting concern - better to do like you suggested in my opinion. You can simplify it a little:

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

Since you have a public Property with a Setter, every time you resolve your object from Windsor, it will also try to set any public properties with appropriate values from the container (in your case, an ILogger which your facility will populate into Windsor).

Meaning, if you resolve the Class from Windsor, this will be set. But not if you do new Class().

That's atleast how I understand it.

The other approach is to use constructors, meaning if you have a constructor named

public Class(ILogger logger) it will be instantiated with ILogger as a parameter.

Example:


var yourClassObject = Kernel.Resolve<IClass>();

IF you don't have an interface specification (and registered as such), you will need to register your component as the concrete type if you want to resolve it using that concrete type(and not by interface).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!