5

尝试注册我的 DbContext 时,Simple Inject 引发以下异常。

提供的连接字符串无效,因为它包含的映射或元数据信息不足。参数名称:连接字符串

我是 DI 的新手,可能会遗漏一些相当明显的东西。连接字符串看起来不错。它与通常用于创建 DbContext 的相同。我在这里尝试解决方案

public static class SimpleInjectorInitializer
{
    /// <summary>Initialize the container and register 
    // it as MVC3 Dependency Resolver.</summary>
    public static void Initialize()
    {
        var container = new Container();            
        InitializeContainer(container);
        container.RegisterMvcControllers(
            Assembly.GetExecutingAssembly());            
        container.RegisterMvcAttributeFilterProvider();       
        container.Verify();            
        DependencyResolver.SetResolver(
            new SimpleInjectorDependencyResolver(container));
    }

    private static void InitializeContainer(
        Container container)
    {
    }
}

更新:我仍然没有解决我的问题,但它与Ninject的这个问题非常相似

堆栈跟踪:

System.InvalidOperationException was unhandled by user code
  Message=The configuration is invalid. Creating the instance for type _AccountController failed. Error occurred while trying to get an instance of type _AccountController. The type initializer for 'Web.Controllers._AccountController' threw an exception.
  Source=SimpleInjector
  StackTrace:
       at SimpleInjector.Helpers.Verify(IInstanceProducer instanceProducer, Type serviceType)
       at SimpleInjector.Container.ValidateRegistrations()
       at SimpleInjector.Container.Verify()
       at Web.App_Start.SimpleInjectorInitializer.Initialize() in C:\workspace\BrowsarServer\QARSite\Web\App_Start\SimpleInjectorInitializer.cs:line 24
  InnerException: SimpleInjector.ActivationException
       Message=Error occurred while trying to get an instance of type _AccountController. The type initializer for 'Web.Controllers._AccountController' threw an exception.
       Source=SimpleInjector
       StackTrace:
            at SimpleInjector.InstanceProducers.InstanceProducer.ThrowErrorWhileTryingToGetInstanceOfType(Exception innerException)
            at SimpleInjector.InstanceProducers.InstanceProducer.GetInstance()
            at SimpleInjector.Helpers.Verify(IInstanceProducer instanceProducer, Type serviceType)
       InnerException: System.TypeInitializationException
            Message=The type initializer for 'Web.Controllers._AccountController' threw an exception.
            Source=Web
            TypeName=Web.Controllers._AccountController
            StackTrace:
                 at Web.Controllers._AccountController..ctor()
                 at lambda_method(Closure )
                 at SimpleInjector.InstanceProducers.InstanceProducer.GetInstance()
            InnerException: System.ArgumentException
                 Message=The supplied connection string is not valid, because it contains insufficient mapping or metadata information.
Parameter name: connectionString
                 Source=System.Data.Entity
                 ParamName=connectionString
                 StackTrace:
                      at System.Data.Objects.ObjectContext..ctor(EntityConnection connection, Boolean isConnectionConstructor)
                      at System.Data.Objects.ObjectContext..ctor(String connectionString, String defaultContainerName)
                      at Web.Models.BrowsarEntities..ctor() in C:\workspace\BrowsarServer\QARSite\Web\Models\Browsar.Designer.cs:line 90
                      at Web.Controllers._AccountController..cctor() in C:\workspace\BrowsarServer\QARSite\Web\Controllers\_AccountController.cs:line 15
                 InnerException: System.InvalidOperationException
                      Message=Unable to determine application context. The ASP.NET application path could not be resolved.
                      Source=System.Data.Entity
                      StackTrace:
                           at System.Data.Metadata.Edm.AspProxy.GetBuildManagerReferencedAssemblies()
                           at System.Data.Metadata.Edm.DefaultAssemblyResolver.GetAllDiscoverableAssemblies()
                           at System.Data.Metadata.Edm.DefaultAssemblyResolver.GetWildcardAssemblies()
                           at System.Data.Metadata.Edm.MetadataArtifactLoaderCompositeResource.LoadResources(String assemblyName, String resourceName, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver)
                           at System.Data.Metadata.Edm.MetadataArtifactLoaderCompositeResource.CreateResourceLoader(String path, ExtensionCheck extensionCheck, String validExtension, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver)
                           at System.Data.Metadata.Edm.MetadataArtifactLoader.Create(String path, ExtensionCheck extensionCheck, String validExtension, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver)
                           at System.Data.Metadata.Edm.MetadataCache.SplitPaths(String paths)
                           at System.Data.Common.Utils.Memoizer`2.<>c__DisplayClass2.<Evaluate>b__0()
                           at System.Data.Common.Utils.Memoizer`2.Result.GetValue()
                           at System.Data.Common.Utils.Memoizer`2.Evaluate(TArg arg)
                           at System.Data.EntityClient.EntityConnection.GetMetadataWorkspace(Boolean initializeAllCollections)
                           at System.Data.Objects.ObjectContext.RetrieveMetadataWorkspaceFromConnection()
                           at System.Data.Objects.ObjectContext..ctor(EntityConnection connection, Boolean isConnectionConstructor)
                      InnerException: System.Reflection.TargetInvocationException
                           Message=Exception has been thrown by the target of an invocation.
                           Source=mscorlib
                           StackTrace:
                                at System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
                                at System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
                                at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
                                at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
                                at System.Data.Metadata.Edm.AspProxy.GetBuildManagerReferencedAssemblies()
                           InnerException: System.InvalidOperationException
                                Message=This method cannot be called during the application's pre-start initialization stage.
                                Source=System.Web
                                StackTrace:
                                     at System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled()
                                     at System.Web.Compilation.BuildManager.GetReferencedAssemblies()
                                InnerException: 
4

3 回答 3

10

根本原因深藏在内部异常中。检查堆栈跟踪时,您将能够找到造成这种情况的原因。原因在于以下两个内部异常:

InvalidOperationException:无法确定应用程序上下文。无法解析 ASP.NET 应用程序路径。

和:

InvalidOperationException:在应用程序的预启动初始化阶段无法调用此方法。

换句话说,这个异常是由时序问题引起的。我不确定您是否可以更改连接字符串来解决此问题,但您也可以将初始化移到启动应用程序的稍后时刻。您可以按如下方式执行此操作:

  1. 删除SimpleInjectorInitializer.cs类的[assembly: WebActivator.PreApplicationStartMethod](顶行) 。
  2. 在全局 asax 事件中添加对该SimpleInjectorInitializer.Initialize()方法的调用。Application_Start()

完成此操作后,对象图的初始化(尤其是验证)在预初始化状态之后完成,这对于 ASP.NET 环境中的 EF 来说似乎为时过早。

另一种选择是从方法中删除container.Verify();调用SimpleInjectorInitializer.Initialize,因为早期验证过程正在扼杀你。但是,请先阅读此验证容器的配置,以查看替代方案,然后再执行此操作。

于 2012-06-16T00:12:26.567 回答
1

尽管您使用了一个类DbContext,但它看起来像是从ObjectContext. 在这种情况下,您应该使用 anEntityConnectionStringBuilder来构建连接字符串。

于 2012-06-15T06:48:54.367 回答
0

您可能会丢失连接字符串中的一些元数据信息。例如实体框架在连接字符串中有一些特殊的元数据,请参见下面的示例:

<add name="MyEntities" connectionString="metadata=res://*/MyEntitiesStore.csdl|res://*/MyEntitiesStore.ssdl|res://*/MyEntitiesStore.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=<your server>;Initial Catalog=<your DB>;Integrated Security=False;User ID=<user>;Password=<pass>;MultipleActiveResultSets=True&quot;" 
   providerName="System.Data.EntityClient" />
于 2012-06-14T23:04:20.957 回答