尝试使用Autofac将log4net类注入我的控制器,但是我得到以下异常:
None of the constructors found with ‘Public binding flags’ on
type ‘MvcApplication6.Controllers.HomeController’ can be invoked with the available services and parameters: Cannot resolve parameter ‘log4net.ILog logger’ of constructor ‘Void .ctor(log4net.ILog)’.
我创建了一个模块,使用正确的类型注入Log类:
public class LogInjectionModule : Module { protected override void AttachToComponentRegistration(IComponentRegistry registry,IComponentRegistration registration) { registration.Preparing += OnComponentPreparing; } static void OnComponentPreparing(object sender,PreparingEventArgs e) { var t = e.Component.Activator.LimitType; e.Parameters = e.Parameters.Union(new[] { new ResolvedParameter((p,i) => p.ParameterType == typeof(ILog),(p,i) => LogManager.GetLogger(t)) }); } }
然后我在我的ASP.NET MVC Application_Start方法中注册该模块:
protected void Application_Start() { ContainerBuilder builder = new ContainerBuilder(); builder.RegisterControllers(typeof (MvcApplication).Assembly) ; var container = builder.Build() ; DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); builder.RegisterModule(new LogInjectionModule()); AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); }
namespace MvcApplication6.Controllers { public class HomeController : Controller { ILog _log; public HomeController(ILog logger) { _log = logger; } public ActionResult Index() { ViewBag.Message = "Welcome to ASP.NET MVC!"; _log.Info("Log message from Index()"); return View(); } public ActionResult About() { _log.Info("Log message from About()"); return View(); } } }
我相信我错过了一步,所以任何帮助都会受到赞赏.
解决方法
我不确定这是否会导致您的问题,但您应该在调用builder.Build()之前尝试将模块添加到ContainerBuilder中;
像这样的东西:
ContainerBuilder builder = new ContainerBuilder(); builder.RegisterControllers(typeof (MvcApplication).Assembly) ; builder.RegisterModule(new LogInjectionModule()); var container = builder.Build() ; DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
另一个建议是不注入记录器.通常当我设计一个类时,使用构造函数依赖项,我尝试表达我正在建模的组件的逻辑业务依赖性.日志记录主要是与应用程序正交的实现细节.至少使用log4net,您可以在需要使用LogManager.GetLogger(类型)创建的日志记录的任何类中拥有静态成员.为了便于添加记录器,您可以使用Visual Studio代码段.