在ASP.NET CORE 2.0中,如何将运行时参数(字符串类型)(例如动态连接字符串)作为依赖项传递给我的服务。字符串参数值将是动态的,并取自HttpContext。
我无法理解如何使用Controller-> Service-> Repository类中的DI传递运行时参数值?
下面的代码是我正在使用的代码。请引导我。
public class AccountController : BaseController//Controller
{
ILogger<AccountController> _logger;
private IUserService _userService;
public AccountController(
ILogger<AccountController> logger
, IUserService userService
) {
_logger = logger;
_userService = userService;
}
public class UserService : IUserService
{
private readonly IUserRepository _userRepository;
private readonly IRoleRepository _roleRepository;
public UserService(
IUserRepository userRepository
,IRoleRepository roleRepository
)
{
_userRepository = userRepository;
_roleRepository = roleRepository;
}
public class UserRepository : DbProvider, IUserRepository
{
private IConfiguration _configuration;
private DatabaseSetting _databaseSetting;
public UserRepository(IConfiguration configuration, IOptions<DatabaseSetting> databaseSetting) : base(configuration, databaseSetting)
{
_configuration = configuration;
_databaseSetting = databaseSetting.Value;
}
public static class StartupExtensions
{
public static IServiceCollection AddCloudscribeCore(this IServiceCollection services, IConfiguration configuration)
{
// Add application repository.
services.AddSingleton<AuthAttributeFilter>();
#region Add Repository Dependency Here
services.AddTransient<IUserRepository, UserRepository>();
services.AddTransient<IRoleRepository, RoleRepository>();
#endregion Repository Dependency
#region Add Service Dependency Here
services.AddTransient<ICompanyService, CompanyService>();
services.AddTransient<IUserService, UserService>();
#endregion Service Dependency
services.Configure<DatabaseSetting>(options =>
{
options.DBProvider = configuration["DatabaseSetting:DBProvider"];
options.ConnectionString = configuration["DatabaseSetting:ConnectionString"];
});
return services;
}
}
答案 0 :(得分:0)
要访问HttpContext
和Service
中的Repository
,不需要从Controller传递,请尝试IHttpContextAccessor
。
public class UserRepository : DbProvider, IUserRepository
{
private IConfiguration _configuration;
private DatabaseSetting _databaseSetting;
private readonly IHttpContextAccessor _accessor;
public UserRepository(IConfiguration configuration, IOptions<DatabaseSetting> databaseSetting, IHttpContextAccessor accessor) : base(configuration, databaseSetting)
{
_configuration = configuration;
_databaseSetting = databaseSetting.Value;
_accessor = accessor;
}
然后,您可以通过HttpContext
访问_accessor.HttpContext
。