【问题标题】:How to correctly inject service in constructor ?如何在构造函数中正确注入服务?
【发布时间】:2018-11-23 03:03:57
【问题描述】:

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

public interface ICustomerService
{
    string Operation();
}

还有一个实现上述接口服务

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

现在我声明一个 unity 容器 以使用 依赖注入模式 和一个名为 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 注册到容器中。容器在解析控制器时会注入依赖
  • 有了Core 2,一切都是控制台应用,包括Web API和Web App。服务是从构造函数的参数自动注入的。你不需要空的默认构造函数。

标签: c# dependency-injection unity-container


【解决方案1】:

在容器中注册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());
    }
}

【讨论】:

    猜你喜欢
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-25
    相关资源
    最近更新 更多