尝试使用Autofac将log4net类注入我的控制器,但是我得到以下异常:
可以使用可用的服务和参数调用在'MvcApplication6.Controllers.HomeController'类型上找到'公共绑定标志'的构造函数:无法解析构造函数'void .ctor(log4net.ILog)的参数'log4net.ILog logger' ".
我创建了一个模块,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))
});
}
}
Run Code Online (Sandbox Code Playgroud)
然后我在我的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()); …
Run Code Online (Sandbox Code Playgroud)