2013-07-03 5 views
5

У меня проблемы с проектом 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), и я «Дайте любую помощь.

+2

VS2010 поставляется с .NET 4.0, но vs2012 с .net 4.5 так разница в рамки версии вызывает проблему не Visual Studio. Вы можете попытаться запустить intnet .net 4.5 на машине vs2010 или попытаться использовать более старую версию Autofac, например 2.6, чтобы узнать, работает ли она в обеих средах. – nemesv

+1

'InvalidProgramException' - кажется ошибкой .NET Framework, когда Autofac пытается создать резольвер. –

+0

@nemesv Вы можете добавить пакет Microsoft Bcl для доступа к большинству функций 4.5 под 4.0. (Но будьте осторожны, они могут создавать беспорядок при использовании источника-контроля) –

ответ

0

Привет, я не тестирую это в VS 2010, потому что у меня его нет. Но в моем VS 2013 работает отлично.

public static class DependencyInjection 
    { 
     public static void Init() 
     { 
      // Create the container builder. 
      var builder = new ContainerBuilder(); 

      //Register controllers 
      builder.RegisterControllers(Assembly.GetExecutingAssembly()); 

      // Register other dependencies. 
      builder.RegisterType<SessionStateProvider>().As<IStateProvider>().InstancePerHttpRequest(); 

      // Build the container. 
      var container = builder.Build(); 

      //Configure ASP.NET MVC the dependency resolver 
      DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); 

     } 
    } 

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); 
    } 
} 

public interface IStateProvider 
{ 
    object this[string key] { get; set; } 
    void Remove(string key); 

} 

public class MvcApplication : System.Web.HttpApplication 
{ 
    protected void Application_Start() 
    { 
     AreaRegistration.RegisterAllAreas(); 
     WebApiConfig.Register(GlobalConfiguration.Configuration); 
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
     RouteConfig.RegisterRoutes(RouteTable.Routes); 
     DependencyInjection.Init(); 
     BundleConfig.RegisterBundles(BundleTable.Bundles); 
    } 
} 

public abstract class BaseController : Controller 
{ 
    protected IStateProvider SessionStateProvider { get; private set; } 
    public BaseController() 
    { 
     SessionStateProvider = DependencyResolver.Current.GetService<IStateProvider>(); 
    } 
} 


public class HomeController : BaseController 
{ 

    public ActionResult Index() 
    { 
     SessionStateProvider["1"] = 2; 
     return View(); 
    } 

} 

Autofac ->https://www.nuget.org/packages/Autofac.Mvc4/