Unity, RegisterType <> and Singleton

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?

+6
source share
1 answer

Try it and see if it helps.

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

Perhaps, if you yourself decide the parameter for your constructor, you, in fact, go to a specific instance, which leads to the fact that it is single.

+9
source

Source: https://habr.com/ru/post/894649/


All Articles