Castle and NLog change connection string at runtime

别等时光非礼了梦想. 提交于 2019-12-11 05:28:57

问题


i am using the NLog built in support for castle and trying to find a way to alter the connection string at run time.

this is my latest swing and miss, im sure it has to do the life cycle at this point as all of the configuration is null so i am guessing that castle has not yet wired up the guts on NLog.

    private const string NLogConnectionString = "NLogConnection";

    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.AddFacility<LoggingFacility>(l => l.UseNLog());

        var config = new NLog.Config.LoggingConfiguration();
        var dbtarget = config.FindTargetByName("database") as DatabaseTarget;

        if (dbtarget != null)
        {
            dbtarget.ConnectionString = MethodThatGiveMeConnectionString(NLogConnectionString);
        }
    }

looking at this post it could be an option but based on the way things have been done here i dont want to change that and much prefer just providing the connection string directly to NLog.

looking here I know i can configure this at run time but i much prefer let most of the settings come from the config file and then just override the connection string.


回答1:


So I found a solution that works but not sure it's the best approach.

Using this post as a reference. This comment was the most helpful:

Initially I tried to implement a custom ILoggerFactory and inject it into LoggingFacility via the customLoggerFactory. But that soon proved to be a dead end. Then I looked into the NLog integration and noticed that there's already a NLogFactory that has it's methods marked as virtual. So I was able to derive from this class

The problem the author is solving is different than my own but it got me to come up with this solution:

public class LoggerInstall : IWindsorInstaller
{
    private const string NLogConnectionString = "NLogConnection";

    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        var config = new NLog.Config.LoggingConfiguration();
        container.AddFacility<LoggingFacility>(l => l.LogUsing(new OwnNLogFactory(GetYourConnectionStringMethod(NLogConnectionString))));
    }
}


public class OwnNLogFactory : NLogFactory  
{
    public OwnNLogFactory(string connectionString)
    {
        foreach (var dbTarget in LogManager.Configuration.AllTargets.OfType<DatabaseTarget>().Select(aTarget => aTarget))
        {
            dbTarget.ConnectionString = connectionString;
        }
    }
}

Still not sure this is the best solution but it works for now, would love to see other solutions if anyone has one



来源:https://stackoverflow.com/questions/24499645/castle-and-nlog-change-connection-string-at-runtime

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