0

I'm trying to add a test that validates that all the MVC controllers in my project can resolve successfully. I get them with

MvcControlleractionlist = asm.GetTypes()
            .Where(type => typeof (System.Web.Mvc.Controller).IsAssignableFrom(type));

In the test I try to resolve them with:

foreach (var mvcController in MvcControlleractionlist)
{
    Container.Resolve(mvcController);
}

The error I get is this:

InnerException = {"The PerRequestLifetimeManager can only be used in the context of an HTTP request. Possible causes for this error are using the lifetime manager on a non-ASP.NET application, or using it in a thread that is not associated with the appropriate synchronizati...

I assume MVC in the background registers all the controllers with the PerRequestLifetimeManager. How can I make MVC think the test is running within an HTTP request?

Fran
  • 6,440
  • 1
  • 23
  • 35
MaPi
  • 1,601
  • 3
  • 31
  • 64
  • 1
    Possible related https://stackoverflow.com/questions/33192431/perrequestlifetimemanager-can-only-be-used-in-the-context-of-an-http-request – Hackerman Jan 08 '18 at 17:36
  • I'd flip this test around. I would run your registration code then verify that the types registered in the container match the types in the assembly. I wouldn't actually try to resolve all the types. – Fran Jan 08 '18 at 17:38
  • also add your registration code for the container. – Fran Jan 08 '18 at 17:39
  • Fran thanks, I can do the validation of the services that are registered, but if a new service is created and added to the controller, but not to container the application will fail – MaPi Jan 08 '18 at 17:41

1 Answers1

0

The solution was not resolving the controller, but iterating through the constructor's dependecies.

    protected virtual List<TypeStruct> GetTypesToResolveFromClassType(Type classType)
    {
        var typeToResolves = new List<TypeStruct>();

        var constructors = classType.GetConstructors();
        foreach (ConstructorInfo constructorInfo in constructors)
        {
            var parameterInfos = constructorInfo.GetParameters();
            foreach (ParameterInfo parameterInfo in parameterInfos.Where(t => t.ParameterType.IsInterface || t.ParameterType.IsAbstract))
            {
                DependencyAttribute dependencyAttribute = (DependencyAttribute)Attribute.GetCustomAttribute(parameterInfo, typeof(DependencyAttribute));
                var type = parameterInfo.ParameterType;
                typeToResolves.Add(new TypeStruct { type = type, DependencyName = dependencyAttribute?.Name });
            }
        }

        return typeToResolves;
    }
MaPi
  • 1,601
  • 3
  • 31
  • 64