问题
I am new to Autofac and IoC so now I try to build my firs ASP.NET MVC 3 application with IoC.
Here with this code I try manually to register ProductController (in Global.asax).
protected void AutofacIocRegistration()
{
var builder = new ContainerBuilder();
//PRODUCT CONTROLLER
var registration = builder.Register(c => new ProductsController(c.Resolve<IProductRepository>()));
builder.RegisterType<ProductsController>().InstancePerHttpRequest();
SqlProductsRepository productRepository = new SqlProductsRepository(DATABASE_CONNECTION);
builder.RegisterInstance(new ProductsController(productRepository));
IContainer container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
When I build the application for the first time, I get list of 4 products in the HTML page (as I expected), but when I refresh the page or go "next" to other list of products then I get the error
A single instance of controller 'WebUI.Controllers.ProductsController' cannot be used to handle multiple requests. If a custom controller factory is in use, make sure that it creates a new instance of the controller for each request.
As you can see in this code
builder.RegisterType<ProductsController>().InstancePerHttpRequest();
I try to solve this with InstancePerHttpRequest() method but unsuccessful, if you have any suggestion please post.
Thanks for any help in advance.
回答1:
use the below method to register your controllers
builder.RegisterControllers(Assembly.GetExecutingAssembly());
if you are using constructor injection in the controllers you can register your repository like this
builder.RegisterType<SqlProductsRepository>().As<IProductRepository>();
this way it will create the object graph when it needs to create the controller
来源:https://stackoverflow.com/questions/6281579/autofac-handle-multiple-requests-in-asp-net-mvc-3