c# - 无法使用 Autofac 注入对象
问题描述
我是 IoC 和 Autofac 的新手。我创建了一个简单的控制台项目来测试该技术。当我运行应用程序时,我收到此错误:请求的服务“AutoFac.BLL.IEmployeeDetail”尚未注册。以下是我的代码。此行抛出错误: build.Register(y => new Employee(y.Resolve()));
public class Employee
{
IEmployeeDetail _employeeDetail;
public Employee(IEmployeeDetail employeeDetail)
{
_employeeDetail = employeeDetail;
}
public string GetName()
{
return _employeeDetail.Name();
}
}
public class EmployeeDetail : IEmployeeDetail
{
public string Name()
{
return "John Doe";
}
}
public interface IEmployeeDetail
{
string Name();
}
public class Program
{
static void Main(string[] args)
{
var build = new ContainerBuilder();
build.Register(y => new Employee(y.Resolve<IEmployeeDetail>()));
var container = build.Build();
Employee employee = container.Resolve<Employee>();
Console.WriteLine(employee.GetName());
Console.ReadLine();
}
}
解决方案
尝试:
static void Main(string[] args)
{
var build = new ContainerBuilder();
build.Register<EmployeeDetail>().As<IEmployeeDetail>().InstancePerDepenency();
build.Register<Employee>().AsSelf().InstancePerDependency();
var container = build.Build();
Employee employee = container.Resolve<Employee>();
Console.WriteLine(employee.GetName());
Console.ReadLine();
}
解释:
您不仅要注册依赖的类型,还要注册使用这些依赖的类型。基本上你想要解决的一切。
推荐阅读
- firebase - 如何在没有 X 的情况下在 Flutter 中添加适用于 ios 的 firebase SDK - 代码
- javascript - 使用 JavaScript 更新 JSON 文件中的值
- laravel - 使用我的数据库中的数据,使用 Laravel 制作一个真实的表
- concatenation - 在pytorch中连接两个不同形状的火炬张量
- excel - 你可以在excel中编辑csv文件,而不用excel改变“”的格式吗?
- javascript - i18next 更改整个应用程序的语言
- postgresql - Travis-CI 上的 PostgreSQL 12 需要 5 分钟才能启动?
- excel - Excel 排序和过滤中断公式
- java - Android Studio“尚未附加片段”
- javascript - 当我选择文件上传时,react-native-webview 在 Android 上崩溃