What is the best way to register an EF ObjectContext for injection, using Unity?
I tried this:
var environment = new EnvironmentInformationProvider();
container.RegisterType<MyContext>(new MyContext(environment.ConnectionString));
But that results in this error:
Error CS1503 Argument 2: cannot convert from 'MyContext' to
'Microsoft.Practices.Unity.InjectionMember'
And I have no idea how to solve that ... Plus I don't think that sets up instance lifetime.
So, with some digging I found this:
builder.RegisterType<MyContext>()
.As<IMyContext>()
.InstancePerLifetimeScope();
That is Autofac code. Switching to it isn't an option, because I'm working on an existing application (and Unity should be able to do the same).
Assuming the above is what I need, what is the Unity equivalent?
When registering a Type, you're not supposed to pass an instance of that type but (optionally) some data that would help Unity to instantiate that Type upon request (the connection-string in your case):
Your attempt to instantiate the context yourself and register it, could have been compiled using:
But that would cause your context to behave effectively like a Singleton and in the case of an Entity Framework context, it's a known anti-pattern that will put you in lots of trouble.