我在我的项目中使用 Autofac
作为 DI 工具,并使用 NLog
进行日志记录。
我在将 NLog
与 Autofac
一起使用时遇到指定记录器名称的问题。
这是 link到我的代码。
如您所见,在 LoggerService.cs 中,第 11 行
我正在构造函数中创建记录器的实例。我怎样才能在那里注入(inject)记录器对象并将记录器名称作为类名?
我们将不胜感激。
更新:我以前看过这个问题。那是关于记录消息中错误的 callsite
信息。我想知道如何使用正确的记录器名称在类中注入(inject)记录器。
更新:在问题本身中添加相关代码。
全局.asax.cs
using Autofac;
using Autofac.Integration.Mvc;
using System.Web.Mvc;
using System.Web.Routing;
using WebApplication2.Utils;
namespace WebApplication2
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
ConfigureAutofac();
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
private void ConfigureAutofac()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterType<MailService>().As<IMailService>();
//builder.RegisterModule<NLogModule>();
builder.RegisterGeneric(typeof(LoggerService<>)).As(typeof(ILoggerService<>)).InstancePerDependency();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}
}
HomeController.cs
using System.Web.Mvc;
using WebApplication2.Utils;
namespace WebApplication2.Controllers
{
public class HomeController : Controller
{
public IMailService mailService { get; set; }
public ILoggerService<HomeController> loggingService;
public HomeController(IMailService mailService, ILoggerService<HomeController> loggingService)
{
this.mailService = mailService;
this.loggingService = loggingService;
}
// GET: Home
public ActionResult Index()
{
loggingService.Debug("Log message from index method");
loggingService.Info("Some info log");
mailService.Send();
return View();
}
}
}
ILoggerService.cs
namespace WebApplication2.Utils
{
public interface ILoggerService<T>
{
void Info(string message);
void Debug(string message);
}
}
LoggerService.cs
using NLog;
namespace WebApplication2.Utils
{
public class LoggerService<T> : ILoggerService<T>
{
public ILogger logger { get; set; }
public LoggerService()
{
logger = LogManager.GetLogger(typeof(T).FullName);
}
public void Debug(string message)
{
logger.Debug(message);
}
public void Info(string message)
{
logger.Info(message);
}
}
}
最佳答案
使用 RegisterGeneric
在注册您的服务时,如下所示。
builder.RegisterGeneric(typeof(LoggerService<>)).As(typeof(ILoggerService<>)).InstancePerRequest();
关于c# - NLog with AutoFac - 如何给记录器名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43454336/