Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在构造函数中正确注入服务?_C#_Dependency Injection_Unity Container - Fatal编程技术网

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

C# 如何在构造函数中正确注入服务?,c#,dependency-injection,unity-container,C#,Dependency Injection,Unity Container,我有一个简单的界面和一个简单的控制台应用程序 public interface ICustomerService { string Operation(); } 以及一个实现上述接口的服务 现在我声明了一个unity容器,以便使用依赖注入模式和一个名为CustomerController的类 var container = new UnityContainer(); container.RegisterType<ICustomerService, CustomerService&

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

public interface ICustomerService
{
    string Operation();
}
以及一个实现上述接口的服务

现在我声明了一个unity容器,以便使用依赖注入模式和一个名为
CustomerController
的类

var container = new UnityContainer();
container.RegisterType<ICustomerService, CustomerService>();
CustomerController c = new CustomerController();
c.Operation();
我知道对于
webapi
MVC
应用程序,它使用了
dependencysolver

public class CustomerController
{
    private readonly ICustomerService _customerService;

    public CustomerController()
    {

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

    public void Operation()
    {
        Console.WriteLine(_customerService.Operation());
    }
}
DependencyResolver.SetResolver(new UnityDependencyResolver(container)); 

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

也向容器注册
CustomerController

public static void Main(string[] args) {

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

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

    //...
}

同时向容器注册
CustomerController
。在解析控制器时,容器将注入依赖项。使用Core 2,所有内容都是控制台应用程序,包括Web API和Web应用程序。服务是从构造函数的参数自动注入的。您不需要空的默认构造函数。
public static void Main(string[] args) {

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

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

    //...
}
public class CustomerController {
    private readonly ICustomerService _customerService;

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

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