Net Core 大量使用依赖注入(Dependency Inject), 打个比方,我们常用的日志组件有Log4Net,NLog等等.
如果我们要随时替换日志组件,那么代码中就不能直接引用某个组件的内容,也不能直接New 某个组件.
而是应该定义一组接口, 然后包装各个组件,实现这个接口. Net Core 自带组件容器, 启动程序时,指定接口对应的实现.
然后在各个页面/Controller 里, 通过构造函数的参数,把要带过去的接口,把容器里的对象自动传过去( 我还不知道是怎么实现的)
各个页面/Controller ,再调用接口的方法. 所谓的面向接口编程.
Net Core 在Microsoft.Extension.Logging定义了ILogger,ILoggerFactory,ILoggerProvider 这几个接口, 日志组件实现这个接口就可以被调用了.
上网查了一下,NLog已经实现了这些接口了,你用Nuget找NLog.Web.AspNetCore 就已经包装好了. 具体文档,请看这篇文章,非常详细.
https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2
我们来看一下代码, 要调用NLog, 在Program.cs里
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConsole();
logging.AddDebug();
})
.UseNLog()
.Build();
}
调用NLog写Log
public class HelloMiddleware
{
private readonly ILogger<HelloMiddleware> _logger;
private readonly RequestDelegate _next;
public HelloMiddleware(RequestDelegate next,ILogger<HelloMiddleware> logger)
{
_next = next;
_logger = logger;
}
public Task Invoke(HttpContext httpContext)
{
httpContext.Response.WriteAsync("Hello in Class Invoke"+ Environment.NewLine);
_logger.LogInformation("******hello middleware*********");
return _next(httpContext);
}
}
我们来看看UseNLog()这个方法的代码,看看做了什么
/// <summary>
/// Use NLog for Dependency Injected loggers.
/// </summary>
public static IWebHostBuilder UseNLog(this IWebHostBuilder builder)
{
return UseNLog(builder, null);
}
/// <summary>
/// Use NLog for Dependency Injected loggers.
/// </summary>
/// <param name="builder"></param>
/// <param name="options">Options for logging to NLog with Dependency Injected loggers</param>
/// <returns></returns>
public static IWebHostBuilder UseNLog(this IWebHostBuilder builder, NLogAspNetCoreOptions options)
{
if (builder == null) throw new ArgumentNullException(nameof(builder));
options = options ?? NLogAspNetCoreOptions.Default;
builder.ConfigureServices(services =>
{
//note: when registering ILoggerFactory, all non NLog stuff and stuff before this will be removed
services.AddSingleton<ILoggerProvider>(serviceProvider =>
{
ServiceLocator.ServiceProvider = serviceProvider;
return new NLogLoggerProvider(options);
});
//note: this one is called before services.AddSingleton<ILoggerFactory>
if (options.RegisterHttpContextAccessor)
{
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
RegisterHiddenAssembliesForCallSite();
});
return builder;
}
而Log4Net 就没有官方的包装,只有一个第三方包装的, 但包装的不好, 日志的配置不是放在Program.cs, 而是放在StartUp.cs. 我打算有时间再重新包装一次.
参考这篇文章
http://www.cnblogs.com/drivenwinder/p/8300881.html
相关文章:
.NET Core 2.0使用NLog
ASP.NET Core 2.0 依赖注入
依赖注入和控制反转
全面理解 ASP.NET Core 依赖注入
原文地址 http://www.cnblogs.com/zitjubiz/p/net_core_daily_2.html
.NET社区新闻,深度好文,欢迎访问公众号文章汇总 http://www.csharpkit.com