c# - 派生类如何注入?
问题描述
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 发生异常
解决方案
你应该这样尝试:
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 参数注册以获取更多信息。
推荐阅读
- swiftui - 创建类似网格的视图,其中网格中的项目位置在 SwiftUI 中是固定的
- javascript - 简单的 ajax api 调用给出错误
- excel - VBA无法转换一般存储的日期
- oracle - 计算两个日期之间的工作日 Oracle Rightnow
- node.js - 使用 CURL 在 Node.js 中是否有任何库 JIRA REST API 调用
- autodesk-forge - 如何在 Autodesk-forge 中以相同的质量更改材质和纹理?
- sql - SELECT 在 MySQL 中对 DECIMAL 无效
- three.js - 使用 PlaneGeometry - Three.js 创建具有弯曲边缘的平面
- laravel - EC2 实例上的 Laravel 项目显示目录结构或错误 404
- python - Python Toast 通知在无 GUI 上不起作用