Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • kapil 21 posts 114 karma points
    Apr 12, 2019 @ 20:56
    kapil
    0

    Failed to create an instance of controller type HomeController (see inner exception)

    Hi,

    I am implementing Autofac for MVC controller, inheriting from RenderMVCController. But I am getting below error. Help on this is greatly appreciated.

    ======Controller : ======

    public class HomeController : RenderMvcController
    {
        private readonly IStateRepository _stateRepository;
        public HomeController(StateRepository stateRepository)
        {
           _stateRepository = stateRepository;
        }
        public override ActionResult Index(ContentModel model)
        {
            HomeViewModel homeModel = SetupDataView(model);
            return View(Constants.HomeView, homeModel);
        }
     }
    

    AutoFac Code:

        private static void ConfigureAutoFac(Composition composition)
    
        {
            var stateRository = new StateRepository();
            var builder = new ContainerBuilder();
            builder.RegisterInstance(new StateRepository()).As<IStateRepository>();
            builder.RegisterType<HomeController>();
    
      builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
    
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    
        }
    

    ======Error:======

    [Exception: Failed to create an instance of controller type MyApplication.HomeController (see inner exception).] Umbraco.Web.Mvc.ContainerControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +141 Umbraco.Web.Mvc.UmbracoControllerFactory.CreateController(RequestContext requestContext, String controllerName) +93 Umbraco.Web.Mvc.RenderControllerFactory.CreateController(RequestContext requestContext, String controllerName) +14 Umbraco.Web.Mvc.MasterControllerFactory.CreateController(RequestContext requestContext, String controllerName) +53 System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +188 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +50 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +443 System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +132 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

  • Paul Johnson 18 posts 109 karma points
    Apr 12, 2019 @ 21:14
    Paul Johnson
    0

    Constructor is asking for concrete type, request the interface instead

  • kapil 21 posts 114 karma points
    Apr 15, 2019 @ 21:27
    kapil
    0

    Thanks for your reply Paul. I changed as you suggested, still same issue:

      public class HomeController : RenderMvcController
        {
            private readonly IStateRepository _stateRepository;
            public HomeController(IStateRepository stateRepository)
            {
               _stateRepository = stateRepository;
            }
        }
    
  • Dave Woestenborghs 3504 posts 12135 karma points MVP 9x admin c-trib
    Apr 16, 2019 @ 06:30
    Dave Woestenborghs
    0

    Hi kapil,

    Can you remove this line from your autofac config :

     builder.RegisterType<HomeController>();
    

    Your controller are normally picked up by the line after that

    builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
    

    But this requires the controller to be in the same assembly as the autofac registration

    Dave

  • Roland Banguiran 7 posts 77 karma points
    Jul 27, 2019 @ 14:20
    Roland Banguiran
    0

    Hi, I'm having the same issue.

    Unresolved dependency [Target Type: UmbracoResumeWebsite.Web.Controllers.SiteLayoutController], [Parameter: navigation(UmbracoResumeWebsite.Helpers.INavigation)], [Requested dependency: ServiceType:UmbracoResumeWebsite.Helpers.INavigation, ServiceName:]

    AutofacComponent.cs

    public class AutofacComponent : IComponent
    {
        public void Initialize()
        {
            var builder = new ContainerBuilder();
            builder.RegisterControllers(typeof(UmbracoApplication).Assembly);
    
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
    }
    

    ApplicationComposer.cs

    public class ApplicationComposer : IUserComposer
    {
        public void Compose(Composition composition)
        {
            composition.Components().Append<AutofacComponent>();
        }
    }
    

    SiteLayoutController.cs

    public class SiteLayoutController : SurfaceController
    {
        private INavigation _navigation;
    
        public SiteLayoutController(INavigation navigation)
        {
            _navigation = navigation;
        }
    
        public ActionResult RenderMainNavigation()
        {
            var root = Umbraco.ContentAtRoot().First();
            return PartialView("Layout/_Navigation", _navigation.GetItems(root, false));
        }
    }
    
  • Paul Johnson 18 posts 109 karma points
    Jul 27, 2019 @ 18:56
    Paul Johnson
    0

    then presumably no concrete classes that implement INavigation are registered in the ioc container.

  • Roland Banguiran 7 posts 77 karma points
    Jul 28, 2019 @ 03:37
    Roland Banguiran
    0

    Hi Paul, I've also tried registering INavigation as below but still the same error.

    builder.RegisterType<Navigation>().As<INavigation>();
    
  • Paul Johnson 18 posts 109 karma points
    Jul 28, 2019 @ 08:59
    Paul Johnson
    0

    Does Navigation have any injected dependencies when it is instantiated? Are they all registered?

  • Roland Banguiran 7 posts 77 karma points
    Jul 28, 2019 @ 09:14
    Roland Banguiran
    0

    Hi Paul, my Navigation class got no constructor.

    public class Navigation : INavigation
    {
        private IPublishedContent Content = null;
        private NavigationList NavigationList = null;
        private const string CACHE_KEY_PREFIX = "umbracoNavigationItems_";
        private double CacheExpiration = 5.0;
    
        /// <summary>
        /// Get all navigation items
        /// </summary>
        /// <param name="publishedContent">The content object</param>
        /// <param name="getFromCache">Whether to get items from cache or not. Default is true.</param>
        public NavigationList GetItems(IPublishedContent publishedContent, bool getFromCache = true)
        {
            NavigationList = new NavigationList();
    
            if (getFromCache)
            {
                var cacheKey = CACHE_KEY_PREFIX + Content.Key;
                NavigationList = GetItemsFromCache(cacheKey);
            }
            else
            {
                NavigationList = GetChildItems(publishedContent);
            }
    
            return NavigationList;
        }
    
        public void SetCacheExpiration(double cacheExpiration)
        {
            CacheExpiration = cacheExpiration;
        }
    
        private NavigationList GetChildItems(IPublishedContent parentContent)
        {
            var childItems = new NavigationList();
            childItems.Items = new List<NavigationListItem>();
    
            foreach (var childContent in parentContent.Children.Where(x => x.IsVisible()))
            {
                childItems.Items.Add(new NavigationListItem
                {
                    Id = childContent.Id,
                    Name = childContent.Name,
                    Url = childContent.Url,
                    Content = childContent,
                    List = childContent.Children.Any() ? GetChildItems(childContent) : new NavigationList()
                });
            }
    
            return childItems;
        }
    
        private NavigationList GetItemsFromCache(string cacheKey)
        {
            ObjectCache cache = MemoryCache.Default;
            var cachedObject = new NavigationList();
    
            if (cache.Contains(cacheKey))
            {
                cachedObject = (NavigationList)cache[cacheKey];
            }
            else
            {
                cachedObject = GetChildItems(Content);
                SetItemsToCache(cacheKey, cachedObject, CacheExpiration);
            }
    
            return cachedObject;
        }
    
        private void SetItemsToCache(string cacheKey, NavigationList cachedObject, double cacheExpiration)
        {
            ObjectCache cache = MemoryCache.Default;
            CacheItemPolicy policy = new CacheItemPolicy();
    
            policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(cacheExpiration);
            cache.Set(cacheKey, cachedObject, policy);
        }
    }
    
Please Sign in or register to post replies

Write your reply to:

Draft