【发布时间】:2022-01-18 11:25:00
【问题描述】:
我想在 StudentProvider 中实现单例模式,然后通过接口访问方法。 StudentProvider 构造函数接受的参数很少。这是没有单例的示例工作代码。
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;
}
}
现在我把它转换成单曲,这里是代码:
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;
}
}
上述单例代码的问题是instance = new StudentProvider(); 需要我无法传递的参数。
如何将参数从单例实例传递给构造函数?
【问题讨论】:
-
你不能,基本上。您没有足够的信息 - 除非您可以在该属性中创建所有必需的对象。我建议现在是放弃单例模式(这会损害可测试性并导致全局状态)转而使用依赖注入的好时机。
标签: c# asp.net asp.net-core design-patterns singleton