Using Autofac, I can register a class to resolve against an interface using property injection, using the following code:
builder.RegisterType<Log4NetAdapter>()
.As<ILogger>()
.PropertiesAutowired()
.InstancePerDependency();
However, my Log4NetAdapter
class has a constructor parameter that requires the name of the calling class. This way, I can log events based upon the name of the calling class.
public class Log4NetAdapter : ILogger
{
private readonly ILog _logger;
public Log4NetAdapter(string logName)
{
_logger = LogManager.GetLogger(logName);
}
...
}
How can I inject the name (i.e. typeof(dependency).Name
) of the dependency into the property-injected class' constructor given that each dependency will have its own Log4NetAdapter
instance?
Update: Building on the LogInjectionModule sample and how Autofac does property injection, I have extended the module to do both constructor and property injection.
Note: I've fixed the type passed to
LogManager
inOnComponentPreparing
to use the declaring type. This makes e.g.Resolve<Func<Service>>
use the correct log type.On how to use the module, here's a sample: