【发布时间】:2019-01-21 04:11:34
【问题描述】:
我是 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();
}
}
【问题讨论】:
-
我会给你一个小费。
_salary不是属性。 stackoverflow.com/questions/295104/… -
@SilentTremor 属性注入肯定会在 Autofac 中工作(我已经使用过很多次了)。不,
public ISalary _salary;不是属性。它是一个领域。这不是争论的焦点。它不是属性。