Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity, RegisterType<> and Singleton objects

I am using Unity to instantiate some objects and I'm finding that no matter what I try, Unity is creating singletons for my objects.

According to the documentation: http://msdn.microsoft.com/en-us/library/dd203242.aspx#Y500

With the following code I should be getting a different instance every time the interface gets 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'm getting a singleton instance.

Below is my declaration. 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, on the second call, in the constructor the inStoreRetailersViewModelBuilder parameter that gets injected is the one generated on the first call (with Chrome).

I've tried using the PerResolveLifetimeManager() and even the PerHttpRequestLifetime() from this thread: MVC, EF - DataContext singleton instance Per-Web-Request in Unity

But nothing seems to give me a brand new instance. Anyone can shed some light on what I may be doing wrong here?

like image 914
Yag Avatar asked Aug 09 '11 15:08

Yag


1 Answers

Try this and see if it helps.

container.RegisterType<IInStoreRetailersViewModelBuilder, InStoreRetailersViewModelBuilder>(
new InjectionConstructor(
    new ResolvedParameter<IRetailerService>()));  
container.RegisterType<CollectController>(
new InjectionConstructor(
    new ResolvedParameter<IInStoreRetailersViewModelBuilder>()));  

Maybe by resolving the parameter to your constructor yourself you are essentially passing in a specific instance which results in it being a singleton.

like image 184
MLF Avatar answered Oct 22 '22 08:10

MLF