Replies: 4 comments 2 replies
-
Hello, Here is an example of how to log all methods of all types which provide the logger as a field: internal class LogFabric : ProjectFabric
{
public override void AmendProject(IProjectAmender amender)
{
amender.With(p => p.Types.Where(
t => t.Fields.Any(
f => f.Name == "_logger"
&& f.Type is INamedType nt
&& nt.IsSubclassOf(t.Compilation.TypeFactory.GetTypeByReflectionName("Microsoft.Extensions.Logging.ILogger"))))
.SelectMany(t => t.Methods)).AddAspect<LogAttribute>();
}
}
public sealed class LogAttribute : OverrideMethodAspect
{
public override dynamic? OverrideMethod()
{
meta.This._logger.LogInformation($"The method {meta.Target.Method.DeclaringType.FullName}.{meta.Target.Method.Name} is being executed.");
return meta.Proceed();
}
} |
Beta Was this translation helpful? Give feedback.
-
@prochan2 Thank you for your answer! |
Beta Was this translation helpful? Give feedback.
-
I see. There are multiple issues here. There cannot be a logger "inside the aspect", because there's no run-time instance of an aspect in Metalama. We could inject the You could also keep a static reference to |
Beta Was this translation helpful? Give feedback.
-
Thank you for the great ideas! Anyway none of them are the real good solution (introduce a field on a class, and add it to the constructor, for getting DI work. :( |
Beta Was this translation helpful? Give feedback.
-
Hi,
I want to use Aspects for logging in an Asp.Net Core project.
I would need Logger or HttpContextAccessor from DI. I have a specially configured Serilog for Logger. Reaching HttpContextAccessor is another quite trivial requirement I think.
How can I get these through DI? I know I should add these for every of my classes where I want to use this Aspect and use meta.This.logger, meta.This.httpContextAccessor in my aspect, but no way.
Could you suggest some good approach for getting DI in Aspects?
Beta Was this translation helpful? Give feedback.
All reactions