Copied to clipboard

Flag this post as spam?

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


  • David McDonnell 53 posts 251 karma points
    Sep 15, 2016 @ 15:43
    David McDonnell
    0

    Umbraco 7 with Unity and Web API and Controller DI

    Hi I am attempting to get Unity working with Umbraco 7.5.3 assembly: 1.0.6092.24019 alongside Web API

    I have Web API working, with Unity with Umbraco installed and have an interface being resolved in a controller constructor. The API works fine, the back office is fine but I get the following error on the home page of the site.

    [ResolutionFailedException: Resolution of the dependency failed, type = "Umbraco.Web.Mvc.RenderMvcController", name = "(none)". Exception occurred while: while resolving. Exception is: InvalidOperationException - The type UmbracoContext does not have an accessible constructor.

    I have the following MVC activator class in start up

    using System.Linq;
    using System.Web.Mvc;
    using Microsoft.Practices.Unity.Mvc;
    using System.Web.Http;
    
    namespace UmbracoWebAPISetup.App_Start
    {
    /// <summary>Provides the bootstrapping for integrating Unity with ASP.NET MVC.</summary>
    public static class UnityWebActivator
    {
        /// <summary>Integrates Unity when the application starts.</summary>
        public static void Start() 
        {
            var container = UnityConfig.GetConfiguredContainer();
    
            FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
            FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));
    
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
    
            GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
    
            // TODO: Uncomment if you want to use PerRequestLifetimeManager
            // Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
        }
    
        /// <summary>Disposes the Unity container when the application is shut down.</summary>
        public static void Shutdown()
        {
            var container = UnityConfig.GetConfiguredContainer();
            container.Dispose();
        }
      }
    }
    

    and the following UnityConfig class file in start up

    using System;
    using Microsoft.Practices.Unity;
    using Microsoft.Practices.Unity.Configuration;
    using CustomServices;
    using Umbraco.Web;
    
    namespace UmbracoWebAPISetup.App_Start
    {
    /// <summary>
    /// Specifies the Unity configuration for the main container.
    /// </summary>
    public class UnityConfig
    {
        #region Unity Container
        private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
        {
            var container = new UnityContainer();
            RegisterTypes(container);
            return container;
        });
    
        /// <summary>
        /// Gets the configured Unity container.
        /// </summary>
        public static IUnityContainer GetConfiguredContainer()
        {
            return container.Value;
        }
        #endregion
    
        /// <summary>Registers the type mappings with the Unity container.</summary>
        /// <param name="container">The unity container to configure.</param>
        /// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to 
        /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
        public static void RegisterTypes(IUnityContainer container)
        {
            // NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
            // container.LoadConfiguration();
    
            // TODO: Register your types here
            // container.RegisterType<IProductRepository, ProductRepository>();
    
    
            container.RegisterType<IPagesService, PagesService>();
        }
      }
    }
    
  • David McDonnell 53 posts 251 karma points
    Sep 15, 2016 @ 16:07
    David McDonnell
    1

    Have managed to resolve this from two articles: A big thanks to: Alex G and Shannon D

    Articles: Unity IOC Error
    Unity IOC Upgrade

    Solution: adding the following to my UnityConfig.cs

    container.RegisterType<UmbracoContext>(
        new ContainerControlledLifetimeManager(),
        new InjectionFactory(c => UmbracoContext.Current))
    .RegisterType<RenderMvcController>(
        new InjectionConstructor(new ResolvedParameter<UmbracoContext>()))
    
  • David McDonnell 53 posts 251 karma points
    Sep 15, 2016 @ 20:42
    David McDonnell
    0

    Turns out that the following line break the back office

    GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
    

    I am unable to create any items.

    I get the error: Server Error, Contact your administrator, check the logs for further information. failed to retrieve data for empty content item type TextPage

    I cannot find any error in logs relating to this

  • David McDonnell 53 posts 251 karma points
    Sep 15, 2016 @ 20:46
    David McDonnell
    0

    enter image description here

    Error from Chrome Debug:

    {"Message":"An error has occurred.","ExceptionMessage":"Object reference not set to an instance of an object.","ExceptionType":"System.NullReferenceException","StackTrace":" at Umbraco.Web.Security.WebSecurity.IsAuthenticated()\r\n at Umbraco.Web.Security.WebSecurity.ValidateCurrentUser(Boolean throwExceptions)\r\n at Umbraco.Web.WebApi.UmbracoAuthorizedApiController.getUmbracoUser()\r\n at Umbraco.Web.Editors.ContentController.GetEmpty(String contentTypeAlias, Int32 parentId)\r\n at lambdamethod(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>cDisplayClass10.9(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.

Please Sign in or register to post replies

Write your reply to:

Draft