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