NLog with AutoFac - 如何给出记录器名称

时间:2017-04-17 15:21:18

标签: c# dependency-injection autofac nlog

我在项目中使用Autofac作为DI工具,在日志中使用NLog

我在使用NLog Autofac时指定记录器名称时遇到问题。

以下是我的代码的link

如您所见,在LoggerService.cs中,第11行

我在构造函数中创建了logger实例。如何在那里注入记录器对象,并将记录器名称作为类名?

任何帮助将不胜感激。

更新:我之前看过这个问题。这与记录的消息中的错误callsite信息有关。我想知道如何在类中注入具有适当记录器名称的记录器。

更新:在问题中添加相关代码。

的Global.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);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

在注册服务时使用RegisterGeneric,如下所示。

builder.RegisterGeneric(typeof(LoggerService<>)).As(typeof(ILoggerService<>)).InstancePerRequest();