I am new to autofac. I am trying to do property injection using this IoC container. The following is my code. I am getting error:
Object reference not set to an instance of an object
At this line: .
return _salary.employeeSalary
; in the GetSalary(int employeeId)
method. In the Program class I even tried, 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();
}
}