I want to set the Entity Framework ObjectContext in a repository class - the ObjectContext being a property of the repository.
I am using Unity XML configuration:
<register type="IUsersRepository" mapTo="SqlUsersRepository" >
<property name="MyObjectContext">
<value value="Per-Request" typeConverter="ObjectContextTypeConverter" />
</property>
</register>
The ObjectContextTypeConverter interprets the value of the property - in this case "Per-Request" - and uses an ObjectContext stored in HttpContext.Current.Items (a per request collection in asp.net).
The ObjectContextTypeConverter.ConvertFrom method is 开发者_StackOverflowonly called once when the Unity configurations is loaded in the Application_Start method of the Global.asax file. Yet when I try to resolve an interface using Unity - the ConvertFrom method won't be called again.
Is there a way to solve this problem?
The reason is that you're setting it as a value. You can set it as a dependency:
<property name="MyObjectContext">
<dependency />
</property>
and inject the context through an in injection factory:
Container.RegisterType<ObjectContext>(
new InjectionFactory(c => GetTheContextInstance()));
精彩评论