Unable to create DbContext for query using simple injector

Simple Inject throws the following exception when trying to register my DbContext.

The connection string is invalid because it contains insufficient mapping information or metadata. Parameter Name: connectionString

I am new to DI and may be missing something pretty obvious. The connection string looks fine. This is the same one that is commonly used to create a DbContext. I tried to find a solution here

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

Update: I still have not solved my problem, but it is very similar to this problem with Ninject

Stack trace:

 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 pre-start initialization stage. Source=System.Web StackTrace: at System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() at System.Web.Compilation.BuildManager.GetReferencedAssemblies() InnerException: 
+4
source share
3 answers

The root cause fades in internal exceptions. When checking the stack trace, you can find the reason for this. The reason is the following two internal exceptions:

InvalidOperationException: Unable to determine application context. The ASP.NET application path cannot be resolved.

and

InvalidOperationException: this method cannot be called during the initialization phase before starting the application.

In other words, this exception is caused by a synchronization problem. I'm not sure that you can change the connection string to solve this problem, but you can also move your initialization to a later point when you start the application. You can do it as follows:

  • Remove [assembly: WebActivator.PreApplicationStartMethod] (top line) of the SimpleInjectorInitializer.cs class.
  • Add a call to the SimpleInjectorInitializer.Initialize() method in the global asax's Application_Start() event.

After this, the initialization (and especially verification) of the object graph is performed after the pre-init state, which seems to be too early for EF in ASP.NET.

Another option is to remove the container.Verify(); call container.Verify(); from the SimpleInjectorInitializer.Initialize method, as this is an early verification process that kills you. However, first read “Check Container Configuration” to see alternatives before doing this.

+8
source

Although you are using the DbContext class, it looks like it is derived from the ObjectContext . In this case, you should use EntityConnectionStringBuilder to create the connection string.

+1
source

You may be missing some metadata data in the connection string. For example, an entity structure has some special metadata in the connection string, see the example below:

 <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" /> 
0
source

All Articles