I have an MVC/WebApi app. I started using Autofac for this solution.
Autofac works. However, randomly I'll receive the error:
An error occurred when trying to create a controller of type 'SomeController'. Make sure that the controller has a parameterless public constructor.
When I clean the solution and rebuild. And no more error. I thought it was my instance of Visual Studio (maybe need to run repair). However, I just tried to release to IIS and I received the error again.
Has anybody encountered this before and can anybody help me out?
Here's Some Code Details:
I have all registrations are done in modules like so:
public class CryptographyModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<AesCryptographyService>()
.As<IAesCryptographyService>()
.InstancePerRequest();
}
}
and I'm using this for bootstrapping Autofac:
public static class Bootstrapper
{
public static void Run()
{
BootStrapAutofac();
}
private static void BootStrapAutofac()
{
var builder = new ContainerBuilder();
var localAssemblies = GetLocalAssemblies();
builder.RegisterApiControllers(localAssemblies);
builder.RegisterControllers(localAssemblies);
builder.RegisterAssemblyModules(localAssemblies);
//build container
var container = builder.Build();
var webApiResolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;
var mvcResolver = new AutofacDependencyResolver(container);
DependencyResolver.SetResolver(mvcResolver);
}
private static Assembly[] GetLocalAssemblies()
{
return AppDomain.CurrentDomain.GetAssemblies()
.Where(a => a.GetName().Name.StartsWith("Loc"))
.ToArray();
}
}