首页 > 解决方案 > 无法使用 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();
    }
}

标签: c#autofac

解决方案


尝试:

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();
}

解释:

您不仅要注册依赖的类型,还要注册使用这些依赖的类型。基本上你想要解决的一切。


推荐阅读