简化Unity Container Resolve表达式

时间:2015-10-03 09:19:36

标签: c# dependencies unity-container

我是依赖注入和Microsoft Unity IoC的新手。我的场景如下:

员工级:

class Employee
{
    private readonly ISalaryCalculation _salaryCalculationCalculator;

    public Employee(ISalaryCalculation salaryCalculationCalculator)
    {
        _salaryCalculationCalculator = salaryCalculationCalculator;
        BaseSalary = 42;
    }

    public string Firstname { get; set; }

    public string Lastname { get; set; }

    public int Age { get; set; }

    public int BaseSalary { get; set; }

    public int CalcSalary()
    {
        return _salaryCalculationCalculator.CalcSalary(BaseSalary);
    }
}

我的SalaryCalculation-Interface

有两种不同的实现方式
interface ISalaryCalculation
{
    int CalcSalary(int baseSalary);
}

我的Unity设置是:

static void Main(string[] args)
{
    UnityContainer unityContainer = new UnityContainer();
    unityContainer.RegisterType<Employee>();

    unityContainer.RegisterType<ISalaryCalculation, BossSalaryCalculation>("Boss");
    unityContainer.RegisterType<ISalaryCalculation, NormalSalaryCalculation>("Normal");

    var employee = unityContainer.Resolve<Employee>(new DependencyOverride(typeof(ISalaryCalculation),unityContainer.Resolve<ISalaryCalculation>("Boss")));
    Console.WriteLine(employee.CalcSalary());
}

使用Unity有没有更智能的方法来实现这一目标?因为每当我实例化一个新的Employee时,我都必须传递其salaryCalculation逻辑。

1 个答案:

答案 0 :(得分:0)

根据某些条件,您只能注册一个实现:

static void Main(string[] args)
{
    UnityContainer unityContainer = new UnityContainer();
    unityContainer.RegisterType<Employee>();

    if (someCondition)
    {
        unityContainer.RegisterType<ISalaryCalculation, BossSalaryCalculation>("Boss");
    }
    else
    {
        unityContainer.RegisterType<ISalaryCalculation, NormalSalaryCalculation>("Normal");
    }
    var employee = unityContainer.Resolve<Employee>();
    Console.WriteLine(employee.CalcSalary());
}

另一种方法 - 使用ResolvedParameter:

static void Main(string[] args)
{
    UnityContainer unityContainer = new UnityContainer();
    unityContainer.RegisterType<Employee>();

    unityContainer.RegisterType<ISalaryCalculation, BossSalaryCalculation>("Boss");
    unityContainer.RegisterType<ISalaryCalculation, NormalSalaryCalculation>("Normal");

    var employee = unityContainer.Resolve<Employee>(new ParameterOverride("salaryCalculationCalculator", new ResolvedParameter<ISalaryCalculation>("Boss")));
    Console.WriteLine(employee.CalcSalary());
}