Using Serilog in ASP.Net Core solution with multiple project

Boucourt 105 Reputation points
2024-01-03T22:45:15.4466667+00:00

I have a ASP.NET Core solution with 3 projects.

APIProject

EntitiesProject

ServicesProject

In order to keep my EndPoint with minimum code, I transferred all the business related code in the Service Project.

In the API project I configure Serilog.

It works fine. I use Dependency Injection to the controller.

public UserController(ApplicationDbContext context,
					UserManager<ApplicationUser> userManager, 
					RoleManager<IdentityRole> roleManager,
					SignInManager<ApplicationUser> sisgnInManager,
					ILogger<AdminController> logger)
{
	_context = context;
	_userManager = userManager;
	_roleManager = roleManager;
	_signInManager = sisgnInManager;
	_logger = logger;
}

In order to keep my EndPoint with minimum code, I transferred all the business related code in the Service Project.

In the API project I configure Serilog.

It works fine. I use Dependency Injection to the controller.

public UserController(ApplicationDbContext context,
													UserManager<ApplicationUser> userManager, 
													RoleManager<IdentityRole> roleManager,
													SignInManager<ApplicationUser> sisgnInManager,
													ILogger<AdminController> logger)
		{
			_context = context;
			_userManager = userManager;
			_roleManager = roleManager;
			_signInManager = sisgnInManager;
			_logger = logger;
		}

One of the endpoints of the UserController is Login.

		[HttpPost]
		[AllowAnonymous]
		[Authorize("NotAuthenticated")]
		[Route("user/login")]
		public async Task<IActionResult> Login(LoginDTO loginDTO)
		{
			if (!ModelState.IsValid)
			{
				ViewBag.Errors = ModelState.Values.SelectMany(temp => temp.Errors).Select(temp => temp.ErrorMessage);
				return View(loginDTO);
			}

			LoginLogoutServices _loginService = new LoginLogoutServices(_context,
													_userManager,
													 _roleManager,
													 _signInManager
													 );

			ServicesResult result = await _loginService.Login(loginDTO);
			
			if (result.Success) // Si c'est bon on retourne +++++++++++++++++++++
			{
				string leMessage = result.Message[0];
				return RedirectToAction("Home", "Admin",  new {lemessage = leMessage }); 
			}

			.....
		}
		

I cannot pass _logger as a parameter to LoginLogoutServices and DI does not work in the Class library.

How can I use Serilog in my Service Library?

Thank you.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,612 questions
{count} votes

Accepted answer
  1. 2024-01-06T16:47:34.7666667+00:00

    There are no technical reasons why you shouldn't be able to pass the logger to the library class. For example, this is possible:

    public class LoginLogoutServices
    {
        private ILogger<LoginLogoutServices> Logger { get; }
        public LoginLogoutServices(ILogger<LoginLogoutServices> logger)
        {
            Logger = logger;
        }
    }
    

    The only requirement would be for your services project to have a direct or indirect reference to the Microsoft.Extensions.Logging.Abstractions NuGet package, where the definition of the ILogger<T> interface lives.

    With this in place, you should also be able to register the LoginLogoutServices class in the IoC container in the Program.cs class:

    builder.Services.AddScoped<LoginLogoutServices>();
    

    With this also in place, you should stop instantiating your LoginLogoutServices class by "hand", and instead have it requested via the controller's constructor:

    public class MyController : ApiController
    {
        private LoginLogoutServices LoginLogoutServices { get; }
    
        public MyController(LoginLogoutServices loginLogoutServices)
        {
            LoginLogoutServices = loginLogoutServices;
        }
    }
    

    Now you just use the LoginLogoutServices property instead of local variables like the _loginService you show in your original post.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.