У меня проблемы с проектом MVC4, который с успехом работает отлично на одном компьютере (VS 2012), но не на другом (VS 2010).Constructor Constructor Autofac
(Надеюсь, что конфликтующие версии VS не проблема, но проект изначально появился на компьютере VS2010, я немного поработал в 2012 году, и теперь я пытаюсь вернуть его в 2010 году.)
я получаю «Убедитесь, что контроллер имеет без параметров общественного конструктора» ошибка, но я думаю, что мой контроллер имеет по умолчанию один:
public class HomeController : AuthorizedControllerBase
{
public ViewResult Index()
{
return View();
}
}
код, который бросает ошибка в моем ControllerFactory:
public class ControllerFactory : DefaultControllerFactory
{
private readonly IStateProvider _sessionStateProvider;
public ControllerFactory(IStateProvider aStateProvider)
{
_sessionStateProvider = aStateProvider;
}
public override IController CreateController
(System.Web.Routing.RequestContext requestContext, string controllerName)
{
IController controller = base.CreateController(requestContext, controllerName);
if (controller is BaseController)
{
var baseController = (BaseController)controller; // ***This line***
baseController.SessionData = _sessionStateProvider;
}
return controller;
}
}
я видел вопрос подобный этому, когда интерфейс реализатор не имел открытый конструктор, но опять же, я думаю, что мое действительно есть по умолчанию одно:
public class SessionStateProvider : IStateProvider
{
public object this[string key]
{
get
{
return HttpContext.Current.Session[key];
}
set
{
HttpContext.Current.Session[key] = value;
}
}
public void Remove(string key)
{
HttpContext.Current.Session.Remove(key);
}
}
на основе ответов на другие вопросы и StackTrace, я рассматривая проблемы Autofac. Я просто сделал Install-Package Autofac
и есть последняя (3.0.2) в проекте, и StackTrace выглядит следующим образом:
InnerException: Autofac.Core.DependencyResolutionException
Message=An exception was thrown while executing a resolve operation. See the InnerException for details. ---> Common Language Runtime detected an invalid program. (See inner exception for details.)
Source=Autofac
StackTrace:
at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable`1 parameters)
at Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters)
at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance)
at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable`1 parameters)
at Autofac.ResolutionExtensions.ResolveOptional(IComponentContext context, Type serviceType, IEnumerable`1 parameters)
at Autofac.ResolutionExtensions.ResolveOptional(IComponentContext context, Type serviceType)
at Autofac.Integration.Mvc.AutofacDependencyResolver.GetService(Type serviceType)
at System.Web.Mvc.DefaultControllerFactory.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType)
InnerException: System.InvalidProgramException
Message=Common Language Runtime detected an invalid program.
Source=Autofac
StackTrace:
at Autofac.Core.Activators.Reflection.ConstructorParameterBinding..ctor(ConstructorInfo ci, IEnumerable`1 availableParameters, IComponentContext context)
at Autofac.Core.Activators.Reflection.ReflectionActivator.<>c__DisplayClass5.<GetConstructorBindings>b__4(ConstructorInfo ci)
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Execute()
at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters)
at Autofac.Core.Resolving.InstanceLookup.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters)
at Autofac.Core.Registration.ExternalRegistrySource.<>c__DisplayClass8.<RegistrationsFor>b__3(IComponentContext c, IEnumerable`1 p)
at Autofac.Core.Activators.Delegate.DelegateActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Execute()
at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters)
at Autofac.Core.Resolving.ResolveOperation.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters)
at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable`1 parameters)
Это происходит, даже если я действительно регистрации IStateProvider так: builder.Register(context => new SessionStateProvider()).As<IStateProvider>();
в ContainerBuilder.BuildContainer()
. В Global.asax я также зарегистрировать ControllerFactory:
protected void Application_Start()
{
Container = ContainerBuilder.BuildContainer();
var autofacDependencyResolver = new AutofacDependencyResolver(Container);
DependencyResolver.SetResolver(autofacDependencyResolver);
ControllerBuilder.Current.SetControllerFactory(new ControllerFactory(Container.Resolve<IStateProvider>()));
Application_Start_MVC();
}
я не уверен, что следующие возможные шаги для пытаться решить эту проблему (я выход из моей глубины разбора StackTrace Autofac), и я «Дайте любую помощь.
VS2010 поставляется с .NET 4.0, но vs2012 с .net 4.5 так разница в рамки версии вызывает проблему не Visual Studio. Вы можете попытаться запустить intnet .net 4.5 на машине vs2010 или попытаться использовать более старую версию Autofac, например 2.6, чтобы узнать, работает ли она в обеих средах. – nemesv
'InvalidProgramException' - кажется ошибкой .NET Framework, когда Autofac пытается создать резольвер. –
@nemesv Вы можете добавить пакет Microsoft Bcl для доступа к большинству функций 4.5 под 4.0. (Но будьте осторожны, они могут создавать беспорядок при использовании источника-контроля) –