How to inject dependency name as a constructor parameter

后端 未结 2 991
故里飘歌
故里飘歌 2021-01-05 22:20

Using Autofac, I can register a class to resolve against an interface using property injection, using the following code:

builder.RegisterType

        
2条回答
  •  无人及你
    2021-01-05 22:57

    You only use logName to effectively resolve by name an ILog, so why not just inject an ILog?

    public class Log4NetAdapter : ILogger
    {
        private readonly ILog _logger;
    
        public Log4NetAdapter(ILog logger)
        {
            _logger = logger;
        }
    
        ...
    }
    

    OK, so now I've just moved the problem a bit, but I've also made this less coupled to other classes, namely the LogManager.

    So if I was using unity, I would then do this to ensure I get the right logger:

    var childContainer = container.CreateChildContainer();
    childContainer.RegisterInstance(LogManager.GetLogger(logName));
    var adaptor = childContainer.Resolve();
    

    The child container prevents any other code getting access to that ILog. You can do this as high up as you like, I don't know any more about your code.

提交回复
热议问题