簡體   English   中英

無法使用Autofac注入對象

[英]Unable to inject object using 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();
}

闡釋:

您不僅必須注冊屬於依賴關系的類型,還必須注冊使用這些依賴關系的類型。 基本上,您要解決的所有問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM