【问题标题】:Unity Bootstrapper from NuGet is throwing error on App_Start来自 NuGet 的 Unity Bootstrapper 在 App_Start 上引发错误
【发布时间】:2013-12-07 16:54:51
【问题描述】:

适用于 Unity 3.0 的 Microsoft Unity Bootstrapper 在此行抛出错误:

FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));

出现以下错误:

“System.ArrayTypeMismatchException”类型的异常发生在 mscorlib.dll 但未在用户代码中处理

附加信息:尝试将元素作为类型访问 与数组不兼容。

完整的代码在这里,这都是由从 nuget 下载的引导程序预先制作和编写的。

引导程序生成的文件 App_Start/UnityMVCActivator.cs

using System.Linq;
using System.Web.Mvc;
using Microsoft.Practices.Unity.Mvc;

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(WebApplication.WebUI.App_Start.UnityWebActivator), "Start")]

namespace WebApplication.WebUI.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));

            // TODO: Uncomment if you want to use PerRequestLifetimeManager
            // Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
        }
    }
}

引导程序生成的文件 App_Start/UnityConfig.cs

using System;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using WebApplication.Domain.Abstract;
using WebApplication.Domain.Concrete;

namespace WebApplication.WebUI.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, EFProductRepository>();
        }
    }
}

有什么想法吗?

#region Assembly Microsoft.Practices.Unity.Mvc.dll, v3.0.0.0
// C:\Users\James\Documents\Visual Studio 2013\Projects\Application\packages\Unity.Mvc.3.0.1304.0\lib\Net45\Microsoft.Practices.Unity.Mvc.dll
#endregion

using Microsoft.Practices.Unity;
using System.Collections.Generic;
using System.Web.Mvc;

namespace Microsoft.Practices.Unity.Mvc
{
    // Summary:
    //     Defines a filter provider for filter attributes that support injection of
    //     Unity dependencies.
    public class UnityFilterAttributeFilterProvider : FilterAttributeFilterProvider
    {
        // Summary:
        //     Initializes a new instance of the Microsoft.Practices.Unity.Mvc.UnityFilterAttributeFilterProvider
        //     class.
        //
        // Parameters:
        //   container:
        //     The Microsoft.Practices.Unity.IUnityContainer that will be used to inject
        //     the filters.
        public UnityFilterAttributeFilterProvider(IUnityContainer container);

        // Summary:
        //     Gets a collection of custom action attributes, and injects them using a Unity
        //     container.
        //
        // Parameters:
        //   controllerContext:
        //     The controller context.
        //
        //   actionDescriptor:
        //     The action descriptor.
        //
        // Returns:
        //     A collection of custom action attributes.
        protected override IEnumerable<FilterAttribute> GetActionAttributes(ControllerContext controllerContext, ActionDescriptor actionDescriptor);
        //
        // Summary:
        //     Gets a collection of controller attributes, and injects them using a Unity
        //     container.
        //
        // Parameters:
        //   controllerContext:
        //     The controller context.
        //
        //   actionDescriptor:
        //     The action descriptor.
        //
        // Returns:
        //     A collection of controller attributes.
        protected override IEnumerable<FilterAttribute> GetControllerAttributes(ControllerContext controllerContext, ActionDescriptor actionDescriptor);
    }
}

Unity 引导程序安装的包

  <package id="Unity" version="3.0.1304.1" targetFramework="net45" />
  <package id="Unity.Mvc" version="3.0.1304.0" targetFramework="net45" />
  <package id="WebActivatorEx" version="2.0.4" targetFramework="net45" />

堆栈:

[ArrayTypeMismatchException: Attempted to access an element as a type incompatible with the array.]
   System.Collections.Generic.List`1.Insert(Int32 index, T item) +58
   System.Collections.ObjectModel.Collection`1.InsertItem(Int32 index, T item) +55
   System.Web.Mvc.FilterProviderCollection.InsertItem(Int32 index, IFilterProvider item) +47
   System.Collections.ObjectModel.Collection`1.Add(T item) +98
   WebApplication.WebUI.App_Start.UnityWebActivator.Start() in c:\Users\James\Documents\Visual Studio 2013\Projects\Application\WebApplication.WebUI\App_Start\UnityMvcActivator.cs:18

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
   System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +192
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +155
   System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +19
   WebActivatorEx.BaseActivationMethodAttribute.InvokeMethod() +236
   WebActivatorEx.ActivationManager.RunActivationMethods(Boolean designerMode) +535
   WebActivatorEx.ActivationManager.RunPreStartMethods(Boolean designerMode) +48
   WebActivatorEx.ActivationManager.Run() +163

[InvalidOperationException: The pre-application start initialization method Run on type WebActivatorEx.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation..]
   System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 methods, Func`1 setHostingEnvironmentCultures) +556
   System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +132
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +102
   System.Web.Compilation.BuildManager.ExecutePreAppStart() +153
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +516

[HttpException (0x80004005): The pre-application start initialization method Run on type WebActivatorEx.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation..]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9882460
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254

【问题讨论】:

  • 您从哪里获得 UnityFilterAttributeFilterProvider ? Nuget 或您创建的。相同的代码对我有用
  • 我只是让 unity bootstrapper 来做......在这种情况下我将卸载并重新安装。
  • 这没有帮助,但我正在添加 Microsoft 编写的过滤器提供程序的代码。
  • 我刚刚发布了我的工作代码,以防万一您无法解决问题。
  • 您的 UnityFilterAttributeFilterProvider 与我的不同。我用 Unity.MVC4,我想你有 Unity.MVC3

标签: c# unity-container visual-studio-2013 asp.net-mvc-5


【解决方案1】:

已更新解决方案

好的,这很棘手。我不知道你是如何获得这种类型的项目的。您可能已从早期版本的 ASP.NET MVC 升级您的项目类型。以下任何方式都是答案。

在您的 Web.Config 的运行时程序集绑定部分,请添加以下内容。

<dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>

这应该可以解决您的问题。

【讨论】:

  • 您是否也使用了引导程序(由 Microsoft 提供)?...所以首先您安装了 Unity 3(由 Microsoft 提供)。然后你安装了名为 Unity MVC4 的 nugget 包(由布拉德文森特人)然后你安装了引导程序?
  • 不管它应该如何工作。这就是我现在所拥有的。它工作正常。
  • github.com/jimmyt1988/WebApplication/tree/master/Application/… - 我会再看看你发布的所有内容。
  • 我能看到的唯一不同是 WebActivatorEx...嗯
  • YEHAAAA,伙计,这该死的工作。天哪,你怎么把那个弄出来的!!!?我永远不会怀疑这一点!非常感谢你。 #virtualbeer - 奇怪的是这是直接开箱即用的全新项目.. Visual Studio 2013 Express.. 不过我以后会记住这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-24
  • 2014-10-02
  • 1970-01-01
  • 2014-06-02
  • 2023-04-03
相关资源
最近更新 更多