【问题标题】:Call a class constructor with parameter inside the parent class在父类中调用带参数的类构造函数
【发布时间】:2020-06-22 18:09:47
【问题描述】:

如你所见,我有这门课:

   public class mybaseclass
    {
        public string token = "";
        private readonly HttpContextAccessor iHTTP;

        public mybaseclass([FromServices]HttpContextAccessor IHTTP)
        {
            //this.httpContext = httpContext;
            iHTTP = IHTTP;
        }
        public mybaseclass()
        {
           
        }
        
      
        protected Task<HttpRequestMessage> CreateHttpRequestMessageAsync(CancellationToken cancellationToken)
        {
           // var t = null;
            try
            {
               // iHTTP.HttpContext.Request.Cookies[key]
               var t = iHTTP.HttpContext.Request.Cookies["Authorization"];
                if (t == null)
                {
                    token = t;
                }
            }
            catch(Exception aaa)
            {

            }
            
                var msg = new HttpRequestMessage();
            // SET THE BEARER AUTH TOKEN
            msg.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
            return Task.FromResult(msg);
        }
    }

并且这个类在这个类中被调用:

public partial class Default1Client : mybaseclass, IDefault1Client
    {
        private string _baseUrl = "";
        private System.Lazy<Newtonsoft.Json.JsonSerializerSettings> _settings;

        public Default1Client(string baseUrl)
        {
            BaseUrl = baseUrl;
            _settings = new System.Lazy<Newtonsoft.Json.JsonSerializerSettings>(CreateSerializerSettings);
        }
// other part of code 
}

我的问题是当我调用 Default1Client 时,该类调用了没有任何参数的 mybaseclass 构造函数,但我需要调用带有 httpcontextaccessor 的构造函数

【问题讨论】:

  • 您究竟是如何创建Default1Client 的实例的?是被注入还是你在使用new
  • @JohnWu 它被注入到我的控制器中,并且我在启动文件中设置了注入
  • 那么你是如何填充baseUrl 的呢?你能告诉我们这样做的代码/配置吗?
  • @JohnWu public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); // services.AddScoped(); services.AddScoped(provider => { return new Default1Client("localhost:44381"); }); services.TryAddSingleton(); services.AddHttpContextAccessor(); }

标签: c# .net class constructor


【解决方案1】:

修改你的构造函数以通过它:

public Default1Client(string baseUrl, HttpContextAccessor contextAccessor) : base(contextAccessor)
{
    //etc....

并在您注册时填充它:

services.AddScoped<IDefault1Client>(provider => { return new Default1Client
(
    "localhost:44381", 
    provider.GetService(typeof(HttpContextAccessor)) as HttpContextAccesor
)}); 

【讨论】:

  • 谢谢。我已经按照你说的修改了我的代码。但是 HttpContextAccessor 再次为空
  • 你能设置断点和/或记录provider.GetService(typeof(HttpContextAccessor))返回的值吗?问题可能出在您向我们展示的代码之外。
【解决方案2】:

在这种情况下,您要指定参数,我们可以使用从您的 baseurl 获取 httpContextAccessor 的函数来注入它们:

    // you can use a function call to get the accessor
    public Default1Client(string baseUrl) : mybaseclass(getHttpContextAccessor(baseUrl))

如果您将与httpcontextaccessor 对应的参数传递给它,则将调用接受参数的构造函数。

【讨论】:

  • 那么我应该如何将 httpcontextaccessor 注入到 default1client 中?
  • 你可以修改DefaultClient的构造函数,把它作为参数,或者有一个函数方法来转换baseUrl并返回httpcontextaccessor。我更新了我的答案以反映这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-28
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-08
相关资源
最近更新 更多