mercredi 15 décembre 2021

Create singleton when private constructor have parameters

I would like to implement singleton pattern in StudentProvider and then access method through interface. StudentProvider constructor accepts few parameters. Here's the sample working code without singleton.

public interface IStudentProvider
{
    Task<StudentViewModel> GetStudentAsync();
}

public class StudentProvider : IStudentProvider
{
    private readonly HttpContext httpContext;
    private readonly IActionContextAccessor actionContextAccessor;
    private readonly IConfiguration configuration;
    private readonly IUnitOfWork unitOfWork;
    private readonly string host;

    public StudentProvider(IHttpContextAccessor _httpContextAccessor, IActionContextAccessor _actionContextAccessor, IConfiguration _configuration, IUnitOfWork _unitOfWork)
    {
        httpContext = _httpContextAccessor.HttpContext;
        
        actionContextAccessor = _actionContextAccessor;
        configuration = _configuration;
        unitOfWork = _unitOfWork;
        host = _httpContextAccessor.HttpContext.Request.Host.Host;
    }

    public async Task<StudentViewModel> GetStudentAsync()
    {
        var std = new StudentViewModel();

        // httpContext, actionContextAccessor, configuration, unitOfWork and host uses here

        return std;
    }
}

Now i converted this into single, here's the code:

public interface IStudentProvider
{
    Task<StudentViewModel> GetStudentAsync();
}

public sealed class StudentProvider : IStudentProvider
{
    private readonly HttpContext httpContext;
    private readonly IActionContextAccessor actionContextAccessor;
    private readonly IConfiguration configuration;
    private readonly IUnitOfWork unitOfWork;
    private readonly string host;

    private static StudentProvider instance = null;

    public static StudentProvider GetInstance
    {
        get
        {
            if (instance == null)
            {
                instance = new StudentProvider();
            }

            return instance;
        }
    }

    private StudentProvider(IHttpContextAccessor _httpContextAccessor, IActionContextAccessor _actionContextAccessor, IConfiguration _configuration, IUnitOfWork _unitOfWork)
    {
        httpContext = _httpContextAccessor.HttpContext;

        actionContextAccessor = _actionContextAccessor;
        configuration = _configuration;
        unitOfWork = _unitOfWork;
        host = _httpContextAccessor.HttpContext.Request.Host.Host;
    }

    public async Task<StudentViewModel> GetStudentAsync()
    {
        var std = new StudentViewModel();

        // httpContext, actionContextAccessor, configuration, unitOfWork and host uses here

        return std;
    }
}

The issue with above singleton code is instance = new StudentProvider(); is expecting parameters which i'm not able to pass.

How do i pass parameters to constructor from singleton instance ?

Aucun commentaire:

Enregistrer un commentaire