开发者

Unity, RegisterType<> and Singleton objects

开发者 https://www.devze.com 2023-03-26 20:09 出处:网络
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.

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 wi开发者_如何转开发ll 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消