0

I've got an MVC app built on EF4.3 and am trying to do some refactoring/cleanup by injecting the DbContext into entities instead of passing it around. I already am using Autofac to pass the context to my controllers and that works great. But using AutowireProperties to set the DbContext property on the entities isn't working (never seems to set the property). Here's my setup:

var builder = new ContainerBuilder();
builder.RegisterControllers( typeof( MvcApplication ).Assembly );
builder.RegisterType<Database.Context>().InstancePerHttpRequest().WithParameter( "viewmodel_mapper", new Models.ViewModelMapper() );
builder.RegisterType<Database.Appointment>().PropertiesAutowired();
builder.RegisterType<DocStore.Context>().InstancePerHttpRequest();
var container = builder.Build();
DependencyResolver.SetResolver( new AutofacDependencyResolver( container ) );

The Database.Appointment has a public property, e.g.:

public Context Context { get; set; }

The short answer is I want to continue to set the context per http request on the controller, then set that same context to an EF entities that have the DbContext property.

John Keene
  • 21
  • 1
  • Is it possible the property type is confused between DocStore.Context and Database.Context? – Rake36 Feb 10 '15 at 16:12
  • I don't think so.. those are two distinct types with completely different inheritance hierarchies (ie, no common interfaces and not assignable to each other). – John Keene Feb 10 '15 at 17:06

1 Answers1

0

While this approach doesn't use Autofac DI, it does solve my problem. It hooks the ObjectMaterialized event on DbContext -- you can then use that to inject whatever value(s) you need. Pretty handy....

http://blog.stephencleary.com/2011/05/getting-objectcontext-from-entityobject.html

John Keene
  • 21
  • 1