Skip to content

Commit

Permalink
Added public method to configure the NLog ServiceLocator
Browse files Browse the repository at this point in the history
  • Loading branch information
snakefoot committed Apr 9, 2018
1 parent 6e82cd5 commit a2aa2e1
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
23 changes: 17 additions & 6 deletions NLog.Web.AspNetCore/AspNetExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,7 @@ public static class AspNetExtensions
#endif
public static void AddNLogWeb(this IApplicationBuilder app)
{
ServiceLocator.ServiceProvider = app.ApplicationServices;
ConfigurationItemFactory.Default.RegisterItemsFromAssembly(typeof(AspNetExtensions).GetTypeInfo().Assembly);
LogManager.AddHiddenAssembly(typeof(AspNetExtensions).GetTypeInfo().Assembly);
app.ApplicationServices.SetupNLogServiceLocator();
}

/// <summary>
Expand Down Expand Up @@ -104,14 +102,12 @@ public static IWebHostBuilder UseNLog(this IWebHostBuilder builder, NLogAspNetCo
if (builder == null) throw new ArgumentNullException(nameof(builder));
options = options ?? NLogAspNetCoreOptions.Default;

ConfigurationItemFactory.Default.RegisterItemsFromAssembly(typeof(AspNetExtensions).GetTypeInfo().Assembly);

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;
serviceProvider.SetupNLogServiceLocator();
return new NLogLoggerProvider(options);
});

Expand All @@ -125,5 +121,20 @@ public static IWebHostBuilder UseNLog(this IWebHostBuilder builder, NLogAspNetCo
}
#endif

/// <summary>
/// Override the default <see cref="IServiceProvider"/> used by the NLog ServiceLocator.
/// NLog ServiceLocator uses the <see cref="IServiceProvider"/> to access context specific services (Ex. <see cref="IHttpContextAccessor"/>)
/// </summary>
/// <remarks>
/// Should only be used if the standard approach for configuring NLog is not enough
/// </remarks>
/// <param name="serviceProvider"></param>
public static IServiceProvider SetupNLogServiceLocator(this IServiceProvider serviceProvider)
{
ServiceLocator.ServiceProvider = serviceProvider;
ConfigurationItemFactory.Default.RegisterItemsFromAssembly(typeof(AspNetExtensions).GetTypeInfo().Assembly);
LogManager.AddHiddenAssembly(typeof(AspNetExtensions).GetTypeInfo().Assembly);
return serviceProvider;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,5 @@ internal static class ServiceLocator
/// The current service provider for reading ASP.NET Core session, request etc.
/// </summary>
public static IServiceProvider ServiceProvider { get; set; }


}
}

0 comments on commit a2aa2e1

Please sign in to comment.