Services collection Add and AddNew

Topics: CAB & Smart Client Software Factory
Oct 20, 2005 at 7:30 AM
originally posted by: sslysaght

I have a question about the difference between Add and AddNew in regard to the WorkItem.Services collection.

In the CAB document, it says

To reuse an existing service instance, or create a new one if there is no existing instance, call the Add method.
To always create a new instance of a service, even if there is an existing instance, call the AddNew method.

In my examples I've tried, I don't see any difference in behavior between
Add and AddNew. For instance I thought in a "child" WorkItem,
Add would not add a local service if the service already existed in the RootWorkItem, but this doesn't seem to be the case.

Can you elaborate on when you would have "existing instances" of services and how it's meant to work in a chain of WorkItems.
In our application WorkItems are being dynamically added and removed and may want to use services in the RootWorkItem or add their own local service.

Thanks for taking the time to reply to questions, I've found the replies on this message board very useful.
Oct 20, 2005 at 8:14 AM
originally posted by: BradWilsonMSFT

I think the document is wrong.

"Add" adds an existing instance of a service to the WorkItem. "AddNew" creates a new instance. The difference is essentially whether you have already instantiated the service object or not. (Also, on a related note, constructor injection is only supported on AddNew, since you were the one who constructed the object ahead of time when using Add.)

One case where you might have an existing instance of a service is when you're adding a single instance of an object which implements two service interfaces. This might look like:

public MyService : IMyService1, IMyService2 { ... }

MyService svc = myWorkItem.Services.AddNew<MyService, IMyService1>();

In either case, if a service already exists on the interface you want to register, you should call Remove() before calling Add() or AddNew().

Hope that helps!