Automatic factory with Common.Logging and Autofac?

落爺英雄遲暮 提交于 2019-11-28 23:41:56

Bailey Ling came up with a great approach that doesn't use stack walking - see post here: http://groups.google.com/group/autofac/msg/704f926779cbe8b3

Remco Schoeman

I've tried to do this too, but I couldn't find a way to get access to the activation stack of autofac (without patching it) to get to the type that is to be injected with the logger instance.

Below is the "Works On My Machine" certified way (Autofac-1.4.3.536)

protected override void Load(ContainerBuilder builder)
        {
            const string loggerName = "Logger.Name";

            builder.
                Register((c, p) => LogManager.GetLogger(p.Named<string>(loggerName))).
                OnPreparing((c, p) =>
            {
                var stack = p.Context.GetActivationStack();
                var requestingType = "default";
                if (stack != null && stack.Length > 1) requestingType = stack[1].Description;
                var parameters = new List<Parameter>(p.Parameters) { new NamedParameter(loggerName, requestingType) };
                p.Parameters = parameters;

            }).
            FactoryScoped();
}

static class ContextExtensions
{
    public static Autofac.Service[] GetActivationStack(this Autofac.IContext context)
    {
        const string notSupportedMessage = "GetActivationStack not supported for this context.";

        var type = context.GetType();
        if (type.FullName != "Autofac.Context") throw new NotSupportedException(notSupportedMessage);

        var field = type.GetField("_componentResolutionStack", BindingFlags.Instance | BindingFlags.NonPublic);
        if (field == null) throw new NotSupportedException(notSupportedMessage);

        var activationStack = field.GetValue(context) as Stack<Autofac.Service>;
        if (activationStack == null) throw new NotSupportedException(notSupportedMessage);

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