我想将ILog注入我的类,而不是ILoggerFactoryAdapter,但ILoggerFactoryAdapter需要调用类的名称(想要记录某些东西的类,所以我可以正确分类)所以Autofac可以以某种方式识别类请求ILog并从工厂自动创建ILog?
答案 0 :(得分:9)
Bailey Ling想出了一个不使用堆栈行走的好方法 - 请参阅此处的帖子:http://groups.google.com/group/autofac/msg/704f926779cbe8b3
答案 1 :(得分:5)
我也试过这样做,但是我找不到一种方法来访问autofac的激活堆栈(没有修补它)来获取要用logger实例注入的类型。 / p>
以下是“我的机器上的工作”认证方式(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();
}
}