我是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();
}
}
答案 0 :(得分:1)
尝试:
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();
}
说明:
不仅必须注册作为依赖项的类型,还必须注册使用这些依赖项的类型。基本上,您要解决的所有问题。