Autofac Unit Testing using RegisterControllers()

Posted by Kane on Stack Overflow See other posts from Stack Overflow or by Kane
Published on 2010-04-10T10:03:27Z Indexed on 2010/04/10 10:13 UTC
Read the original article Hit count: 2109

Filed under:
|
|
|

I am having problems using Autofac 2.1.13 and writing my unit tests for my ASP.NET MV2 application. I can't seem to resolve controllers when using the RegisterControllers method. I have tried using the Resolve<>() and ControllerBuilder.Current.GetControllerFactory().CreateController() methods but to no avail. I am sure that I've missed something simple here so can anyone assist?

This was my first attempt at resolving the HomeController - but does not work.

ContainerBuilder builder = new ContainerBuilder();
builder.RegisterControllers(typeof(HomeController).Assembly);

IContainer container = builder.Build();

// Throws a Throws a A first chance exception of type 'Autofac.Core.Registration.ComponentNotRegisteredException' occurred in Autofac.dll
var homeController = container.Resolve<HomeController>(); 

Similarly this does not work either.

ContainerBuilder builder = new ContainerBuilder();
builder.RegisterControllers(typeof(HomeController).Assembly);

IContainer container = builder.Build();

var containerProvider = new ContainerProvider(container);
ControllerBuilder.Current.SetControllerFactory(new AutofacControllerFactory(containerProvider));

var request = new Mock<HttpRequestBase>(MockBehavior.Loose);
request.Setup(r => r.Path).Returns("Path");
var httpContext = new Mock<HttpContextBase>(MockBehavior.Loose);
httpContext.SetupGet(c => c.Request).Returns(request.Object);

ControllerBuilder.Current.GetControllerFactory().CreateController(new RequestContext(httpContext.Object, new RouteData()), "home");

Any assistance would be greatly appreciated. I should note if I register my controllers without using the RegisterControllers() method my unit tests work. My question would seem to be limited to specifically using the RegisterControllers() method.

© Stack Overflow or respective owner

Related posts about autofac

Related posts about mvc2