tags:

views:

62

answers:

1

Hi,

I have come across a bit of a problem while using Unity and WPF. The scenario is I have a WPF application which follows the MVVM design pattern. A have a module called ViewKDI. Within this module I have a service called ViewKDIService, the ViewKDIService service utilises another service called UserService.

Every time I load the module ViewKDI I want Unity to return me a new instance of both the ViewKDIService and the UserService.

I have put the below in the shell bootstrapper:

Container.RegisterType<IUserService, UserService>();

In the ViewKDI module I have put the following:

Container.RegisterType<IViewKDIService, ViewKDIService>();

Each time the ViewKDI module loads the ViewKDIService constructor is called. However the UserService constructor is only called the first time, this means that I am not getting a new instance of UserService.

I require unity to give me a new instance of UserService too so that I can manage this session separately from the rest of the application.

Any ideas?

Thanks Faisal

+2  A: 

Unity's default behaviour is to create a new instance of each object each time one is requested, so you shouldn't be seeing this behaviour.

From what I can gather from the source code and MSDN documentation (this is a good read), you can specify a "lifetime manager" object when you register a type to tell Unity how the type should be constructed and cached. Using the TransientLifetimeManager (which essentially does no caching) will cause Unity to re-create the class each time. So try this:

Container.RegisterType<IUserService, UserService>(new TransientLifetimeManager());

... and see if it creates a new UserService each time.

Matt Hamilton
thanks I will try this
Faisal