我是autofac的新手。我正在尝试使用这个 IoC 容器进行属性注入。以下是我的代码。我收到错误:
你调用的对象是空的
在这一行: .
return _salary.employeeSalary
; 在GetSalary(int employeeId)
方法中。在我什至尝试过的程序课上,build.RegisterType<Employee>().WithProperty("_salary", new Salary{ employeeId = 5, employeeSalary = 500 });
public interface IEmployee
{
double GetSalary(int employeeId);
}
public interface ISalary
{
int employeeId { get; set; }
double employeeSalary { get; set; }
}
public class Salary : ISalary
{
public int employeeId {get; set;}
public double employeeSalary { get; set; }
}
public class Employee: IEmployee
{
public ISalary _salary;
public double GetSalary(int employeeId)
{
if (employeeId == 5)
{
return _salary.employeeSalary;
}
else
{
return 0;
}
}
}
public class Program
{
static void Main(string[] args)
{
var build = new ContainerBuilder();
build.RegisterType<Salary>().As<ISalary>();
build.RegisterType<Salary>().As<ISalary>().PropertiesAutowired();
var container = build.Build();
Employee employee = container.Resolve<Employee>();
Console.WriteLine(employee.GetSalary(5));
Console.ReadLine();
}
}