代码之家  ›  专栏  ›  技术社区  ›  Mihai Alexandru-Ionut

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

  •  1
  • Mihai Alexandru-Ionut  · 技术社区  · 8 年前

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

    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();
    

    我想把服务注入 客户控制器 .

    public class CustomerController
    {
        private readonly ICustomerService _customerService;
    
        public CustomerController()
        {
    
        }
        [InjectionConstructor]
        public CustomerController(ICustomerService customerService)
        {
            _customerService = customerService;
        }
    
        public void Operation()
        {
            Console.WriteLine(_customerService.Operation());
        }
    }
    

    我知道那是因为 Web API MVC 使用的应用程序 DependencyResolver .

    DependencyResolver.SetResolver(new UnityDependencyResolver(container)); 
    

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

    1 回复  |  直到 8 年前
        1
  •  2
  •   Nkosi    8 年前

    注册 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());
        }
    }