Using Autofac to inject log4net into controller

后端 未结 1 395
生来不讨喜
生来不讨喜 2021-02-09 13:06

Trying to use Autofac to inject a log4net class into my controller, but I get the following exception:

None of the constructors found with \'Public bindin

相关标签:
1条回答
  • 2021-02-09 13:30

    I'm not sure this is causing your problem but you should try to add the module to the ContainerBuilder before calling builder.Build();

    Something like this:

    ContainerBuilder builder = new ContainerBuilder();
    builder.RegisterControllers(typeof (MvcApplication).Assembly) ;
    builder.RegisterModule(new LogInjectionModule());
    
    var container = builder.Build() ;
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); 
    

    Another suggestion is to not inject the logger. Usually when i design a class, with the constructor dependencies i try to express the logical business dependencies of the component i'm modelling. Logging is mostly an implementation detail that is orthogonal to the application. At least with log4net you can have a static member in any class where you need logging that is created with LogManager.GetLogger(type). To facilitate adding the logger you can use a Visual Studio snippet.

    0 讨论(0)
提交回复
热议问题