【发布时间】: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 API 和MVC 应用程序使用DependencyResolver。
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
但是如何在一个简单的控制台应用程序中注入 service?
【问题讨论】:
-
也将
CustomerController注册到容器中。容器在解析控制器时会注入依赖 -
有了Core 2,一切都是控制台应用,包括Web API和Web App。服务是从构造函数的参数自动注入的。你不需要空的默认构造函数。
标签: c# dependency-injection unity-container