我刚开始使用Autofac,所以对于这个新手问题请见谅。我阅读了互联网上解释使用Autofac(或像Structuremap、Unity等其他工具)基础知识的所有手册。但是我发现所有的例子都很基础。我需要了解如何在我的代码中更深入地实现Autofac。让我尝试用这个控制台应用程序的例子来解释我需要了解的内容。
class Program
{
static void Main(string[] args)
{
var container = BuildContainer();
var employeeService = container.Resolve<EmployeeService>();
Employee employee = new Employee
{
EmployeeId = 1,
FirstName = "Peter",
LastName = "Parker",
Designation = "Photographer"
};
employeeService.Print(employee);
}
static IContainer BuildContainer()
{
var builder = new ContainerBuilder();
builder.RegisterType<EmployeeRepository>().As<IEmployeeRepository>();
builder.RegisterType<EmployeeService>();
return builder.Build();
}
}
这很简单易懂。我想要弄清楚的是,当你深入代码时,你如何实现它。在这个例子中,当您执行此行时:
This is simple and easy. What I'm trying to figure out is how do you implement this when you go deeper in the code. In this example, when you execute this line
employeeService.Print(employee);
假设“Print”方法有些复杂,并且需要使用其他依赖项/类来完成其任务。我们仍然在使用Autofac,因此我认为我们需要像上面的示例一样创建这些依赖项。是这样吗?在我的“print”方法内,当我需要使用另一个类时,我必须创建另一个容器,填充它,使用Resolve()等等吗?有更简单的方法吗?一个包含所有所需依赖项的静态类可以在整个解决方案中使用吗?如何实现?希望我表达清楚。也许我无法表达自己的需求。 :( 对不起,我的英语很差。 我还在学习Autofac。
EmployeeService
需要一个IEmployeeRepository
,所以你注册了它。如果EmployeeService
依赖于其他注入到其构造函数中的东西,那么你只需要将其与已有的两个注册一起注册到同一个容器中。当你解析EmployeeService
时,容器将解析它所需的任何内容,即使这些类具有依赖关系,以及这些类所依赖的类,以此类推,只要这些类型都已注册。这就是它如此强大的原因。 - Scott HannenApplicationLogic
构造函数中接受EmployeeService
,并将创建Employee
和调用employeeService.Print(employee)
移至ApplicationLogic.Run()
方法。当然,注入接口而不是具体类型(如下面的答案所指出的)也是一个好建议。 - NightOwl888