国际奥委会统一:注册一个​​实体框架的ObjectContext的依赖注入

问题描述:

什么是注册一个EF ObjectContext的注射,使用统一的最佳方式是什么?

What is the best way to register an EF ObjectContext for injection, using Unity?

我尝试这样做:

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();

这是Autofac code。切换到这是不是一种选择,因为我工作的现有应用程序(和团结应该可以做同样的)。

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):

container.RegisterType<IMyContext, MyContext>(new InjectionConstructor(environment.ConnectionString));

您试图实例自己的背景和登记,本来的编译的使用:

Your attempt to instantiate the context yourself and register it, could have been compiled using:

container.RegisterInstance<IMyContext>(new MyContext(environment.ConnectionString));

但是,这将导致你的背景下表现有效地像一个独立的,并在实体框架范围内的情况下,这是一个已知的反模式,将让你的许多麻烦。

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.