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

How to correctly inject service in constructor ?

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

public interface ICustomerService
{
    string Operation();
}

和一个实现上述 接口.服务

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

现在我声明一个 unity 容器 以便使用 依赖注入模式 和一个 class 称为 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

同时向容器注册 CustomerController

public static void Main(string[] args) {

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

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

    //...
}

container会在解析controller时注入依赖

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

public class CustomerController {
    private readonly ICustomerService _customerService;

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

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