C# IoC控制器实际上是如何工作的?特别是在.NETMVC中?
控制器构造函数:C# IoC控制器实际上是如何工作的?特别是在.NETMVC中?,c#,.net,model-view-controller,autofac,C#,.net,Model View Controller,Autofac,控制器构造函数: IRestaurantData db; public HomeController(IRestaurantData db) { this.db = db; } //集装箱代码 public class ContainerConfig { internal static void RegisterContainer(HttpConfiguration httpConfiguration) { v
IRestaurantData db;
public HomeController(IRestaurantData db)
{
this.db = db;
}
//集装箱代码
public class ContainerConfig
{
internal static void RegisterContainer(HttpConfiguration httpConfiguration)
{
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterApiControllers(typeof(MvcApplication).Assembly);
builder.RegisterType<InMemoryRestaurantData>()
.As<IRestaurantData>()
.SingleInstance();
var container = builder.Build();
// MVC CONTROLLER VERSION
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
// WEBAPI CONTROLLER VERSION
httpConfiguration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}
}
公共类容器配置
{
内部静态无效寄存器容器(HttpConfiguration HttpConfiguration)
{
var builder=new ContainerBuilder();
注册控制器(类型化(MVCAPApplication).Assembly);
构建器.注册表位控制器(类型化(MVCAPApplication).Assembly);
builder.RegisterType()
.As()
.SingleInstance();
var container=builder.Build();
//MVC控制器版本
SetResolver(新的AutofacDependencyResolver(容器));
//WEBAPI控制器版本
httpConfiguration.DependencyResolver=新的AutofacWebApidencyResolver(容器);
}
}
所以我想了解控制反转容器是如何工作的。我参加的课程是使用Autofac创建这些容器。根据我目前的理解,创建这个容器是为了在我用iRestaturantData实例化HomeController时,每次使用它时,容器都会将接口指向InMemoryResataurantData。我能理解很多。我还感到困惑的是,我不明白我的控制器在程序的什么地方被实例化了?有人知道吗?这是由autofac完成的。无论何时从容器请求类,它都将使用默认构造函数为您实例化类型。如果您有一个带参数的构造函数,它将在容器中查找其他已注册的类型,并将实例化一个新对象或获取一个已使用的对象 实例化的类型可以是暂时的(短期的),也可以不是
简言之;当请求对象时。这是我的第一篇帖子!我以后会这么做的谢谢