如何在构造函数中正确注入服务?

时间:2018-06-13 13:43:34

标签: c# dependency-injection unity-container

我有一个简单的界面和一个简单的控制台应用程序。

public interface ICustomerService
{
    string Operation();
}

和一个服务,它实现了上述接口

public class CustomerService : ICustomerService
{
    public string Operation()
    {
        return "operation";
    }
}

现在我宣布一个统一容器,以便使用依赖注入模式和一个名为CustomerController的类。

var container = new UnityContainer();
container.RegisterType<ICustomerService, CustomerService>();
CustomerController c = new CustomerController();
c.Operation();

我想在CustomerController内注入服务。

public class CustomerController
{
    private readonly ICustomerService _customerService;

    public CustomerController()
    {

    }
    [InjectionConstructor]
    public CustomerController(ICustomerService customerService)
    {
        _customerService = customerService;
    }

    public void Operation()
    {
        Console.WriteLine(_customerService.Operation());
    }
}

我知道,对于Web APIMVC应用,它使用了DependencyResolver

DependencyResolver.SetResolver(new UnityDependencyResolver(container)); 

但是如何在一个简单的控制台应用中正确地注入 service

1 个答案:

答案 0 :(得分:2)

同时注册CustomerController和容器。

public static void Main(string[] args) {

    var container = new UnityContainer()
        .RegisterType<ICustomerService, CustomerService>()
        .RegisterType<CustomerController>();

    CustomerController c = container.Resolve<CustomerController>();
    c.Operation();

    //...
}

container将在解析控制器时注入依赖关系

如果仅通过其他构造函数使用依赖项,则实际上不再需要默认构造函数和[InjectionConstructor]属性

public class CustomerController {
    private readonly ICustomerService _customerService;

    [InjectionConstructor]
    public CustomerController(ICustomerService customerService) {
        _customerService = customerService;
    }

    public void Operation() {
        Console.WriteLine(_customerService.Operation());
    }
}