I use Unity to instantiate some objects, and I find that no matter what I try, Unity creates single elements for my objects.
According to the documentation: http://msdn.microsoft.com/en-us/library/dd203242.aspx#Y500
In the following code, I have to get different instances every time the interface is resolved.
IUnityContainer myContainer = new UnityContainer(); // Register a default (un-named) type mapping with a transient lifetime myContainer.RegisterType<IMyObject, MyRealObject>(); // Following code will return a new instance of MyRealObject myContainer.Resolve<IMyObject>();
But instead, I get a singleton instance.
Below is my expression. Global.asax
// This should get me a singleton container.RegisterType<IRetailerService, RetailerService>(new ContainerControlledLifetimeManager(), new InjectionConstructor()); // This is the one giving me trouble. container.RegisterType<IInStoreRetailersViewModelBuilder, InStoreRetailersViewModelBuilder>(new InjectionConstructor(container.Resolve<IRetailerService>())); container.RegisterType<CollectController>(new InjectionConstructor(container.Resolve<IInStoreRetailersViewModelBuilder>()));
controller
private readonly IInStoreRetailersViewModelBuilder _inStoreRetailersViewModelBuilder; public CollectController(IInStoreRetailersViewModelBuilder inStoreRetailersViewModelBuilder) { this._inStoreRetailersViewModelBuilder = inStoreRetailersViewModelBuilder; } public ActionResult Index() { InStoreViewModel viewModel = this._inStoreRetailersViewModelBuilder.WithRetailers().WithPostcode().Build(); }
If I open Chrome and run the Index action, and then I go and open Internet explorer and call the Index action in the second call, in the constructor the inStoreRetailersViewModelBuilder parameter that is entered is the one that was generated during the first call (with Chrome).
I tried using PerResolveLifetimeManager () and even PerHttpRequestLifetime () from this thread: MVC, EF - instance of SingleContext DataContext Per-Web-Request in Unity
But nothing seems to give me a completely new instance. Can anyone shed some light on what I can do wrong here?