Autofac: Register component and resolve depending on resolving parent

Viewed 7712

I'm wanting to register a component to resolve with parameters based on the class that it might be resolving for. (That sounds a bit confusing, so I'll show an example).

Here's an object that uses a logger:

class MyObject : IMyObject
{
    public ILogger Logger;
    public MyObject(ILogger logger)
    {
        Logger = logger;
    }
}

Now the logger that is passed in COULD be different from class to class. So I've got a rather patched idea for how to do that below:

class MyLogger : ILogger
{
    public string Name{get; protected set;}

    public static ILogger GetLogger(string className)
    {
        Name = className;
        MyLogger logger;
        // Do something to choose a logger for that specific class
        return logger;
    }
}

So when I register Logger I want to be able to tell it the className. I'm hoping there's a way to do it similar to this:

ContainerBuilder builder = new ContainerBuilder();

builder.Register<MyLogger>(ctx =>
    {
        string className = //Get resolving class name somehow;
        return MyLogger.GetLogger(className);
    }).As<ILogger>();

builder.Register<MyObject>().As<IMyObject>();

var container = builder.Build();

IMyObject myObj = container.Resolve<IMyObject>();

//myObject.Logger.Name should now == "MyObject"

The reason I want to do it this way is to avoid registering each class I implement with a logger with autofac in code. I want to be able to register all of the objects in xml, and simply have a LoggerModule, that adds this registration.

Thanks in advance!

1 Answers
Related