Correct way to register an ObjectContext EF4 using Unity?

I have problems with EF4 ObjectContext in Unity. In particular, when Unity tries to resolve my ObjectContext with the following code:

container.RegisterType<ObjectContext, MyObjectContext>( new TransientLifetimeManager(), new InjectionConstructor()); 

This gives me:

The specified named connection is either not in the configuration, is not intended to be used with the EntityClient provider, or is invalid.

I assumed that he would be able to use the wired connection that was configured when creating the EF4 data model (used with a constructor without parameters), but it seems to me that I should explicitly pass this to:

 container.RegisterType<ObjectContext, MyObjectContext>( new TransientLifetimeManager(), new InjectionConstructor(connectionString)); 

Also, since this method seems to instantiate my (one-time) ObjectContext, when is this the right place to destroy it?

Or should I do it differently?

Thanks in advance.

+4
source share
1 answer

Exception "The specified named connection is either not found in the configuration that is not intended for use with the EntityClient provider or is invalid." obviously not the result of unsuccessful resolution of the registered type, but this is an EF exception.

An EF designer should create a context with a constructor like this:

 public MyObjectContext() : base("name=MyObjectContext", "MyObjectContext") { ... } 

and added a connection string to app.config / web.config. Assuming that the designer didn’t do it wrong, I rule out that this "named connection" is "not intended to be used with the EntityClient provider or is invalid." It remains that "named connection" "was not found in the configuration".

Have you checked if there is a connection string in the app.config / web.config of the project where you enable the ObjectContext ? For example, if you have an EF model in a separate class library, then EF creates app.config with the corresponding connection string in this project. If you are consuming this model from another project that references your EF class library, you need to copy the connection string manually to app.config / web.config of this project. EF will not consider the configuration of your class library.

As for your question, what is the place for destroying an ObjectContext, the most common answer would be: "When you no longer need it." It is difficult to give advice without knowing your project context. If you need access to data in one way, I think you could write:

 using (var context = container.Resolve<ObjectContext>()) { // your EF operations } 
+2
source

Source: https://habr.com/ru/post/1339522/


All Articles