0

I am trying to use Unity as a resolver for creating my Breeze Web API controllers. Using breakpoints, it seems that the constructor for my AHSEFContextProvider is only being called one time. Breeze requires a new instance each time otherwise the SaveChanges() method doesn't work properly. I'm new to Unity but I thought using the TransientLifetimeManager (which I believe is the default anyway) would cause a new instance to be created each time. Below is the UnityConfig code which is being called from the Global.asax Application_Start. Any ideas on where I'm going wrong?

var container = new UnityContainer();
container.RegisterType<AHSEFContextProvider<TaskDbContext>>(new TransientLifetimeManager(), new InjectionConstructor("ConnectionStringName"));
container.RegisterType<TaskController>(new TransientLifetimeManager(), new InjectionConstructor(container.Resolve<AHSEFContextProvider<TaskDbContext>>()));
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
  • 1
    I think that you probably want to use the `PerHttpRequestLifetimeManager ` for an EF Context. https://msdn.microsoft.com/en-us/library/microsoft.practices.unity.perrequestlifetimemanager%28v=pandp.30%29.aspx . See the following SO post for more info: http://stackoverflow.com/questions/5187562/mvc-ef-datacontext-singleton-instance-per-web-request-in-unity – David Tansey Feb 17 '15 at 17:14
  • Thanks for the tip but it didn't make any difference changing from the TransientLifetimeManager to the PerResolveLifetimeManager. – Jim Wheeler Feb 17 '15 at 17:54
  • 1
    Umm.. That's kind of the desired behavior (or at least should be). You *don't* want multiple instances of your context floating around, even if for some reason you *think* you do. You're going to run into all kinds of issues. There should be one instance of your context per request. Anything more than that is asking for trouble. – Chris Pratt Feb 17 '15 at 20:07

1 Answers1

2

I was able to get this to work properly by adding the [InjectionConstructor] attribute to the constructor on my Breeze controller. Then changing my Unity configuration as follows:

var container = new UnityContainer();
container.RegisterType<AHSEFContextProvider<TaskDbContext>>(new InjectionConstructor("ConnectionStringName"));
container.RegisterType<AHS.Apps.Task.Server.BreezeControllers.TaskController>();
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);