派生类如何注入?

时间:2019-01-31 15:51:49

标签: c# asp.net .net

ASP.Net Core Web API

父类是否没有空的构造函数 派生类Autofac注入?

如果在参数后添加了注入类,则不能使用

  public class A    
  {    
        public A(string e1,string e2){}  
  }

  public class B:A
  {    
        private readonly IProductService _productService;     
        public B(IProductService productService):base(string e1,string e2)
        {
              _productService = productService
        }
        public void test()
        {
              _productService.AddProduct("");
        }
  }

AutoFac没问题配置

_productService发生异常

1 个答案:

答案 0 :(得分:0)

您应该这样尝试:

public B(IProductService productService, string e1,string e2):base(e1,e2)
{
    _productService = productService
}

然后为此类注册配置Autofac:

builder.Register(c => new B(c.Resolve<IProductService>(), "e1_val","e2_val"));

如果B类将在某个时候实现接口,您也可以像这样使用它:

builder.RegisterType<B>().As<IB>()
       .WithParameter("e1", "e1value")
       .WithParameter("e2", "e2value");

请记住,Autofac具有很大的灵活性,请查看Autofac Parameters Register上的文档,以获取更多信息。