首页 > 解决方案 > 派生类如何注入?

问题描述

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 发生异常

标签: c#asp.net.net

解决方案


你应该这样尝试:

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 参数注册以获取更多信息。


推荐阅读