Inversion of Control Bug ?

Topics: CAB & Smart Client Software Factory
Jan 3, 2006 at 4:38 PM
originally posted by: alexsantos

Hi,

Example of code :

public class MyWorkItem: WorkItem, IMyWorkItem
{
public void IMyWorkItem.DoAnyThing()
{
}
public override void OnRunStarted()
{
Items.AddNew<MyView>();
}
}

public class MyView
{
InjectionConstructor
public MyView(ServiceDependency IMyWorkItem workItem)
{
workItem.DoAnyThing();
}
}


This code doen't work because "IMyWorkItem" is not found, but it exists...

I saw that the file "ManagedObjectCollection.cs" find by type using this code :

public ICollection<TItem> FindByType(Type searchType)
{
..
..
foreach (object obj in container)
if (searchType.IsAssignableFrom(obj.GetType()))
result.Add((TItem)obj);
..
..
}

IMyWorkItem.IsAssignableFrom(MyWorkItem.GetType()) return False in code above !


Is it a bug or I'm forget anything ? ...I saw the results in debug mode.
Jan 4, 2006 at 6:45 AM
originally posted by: BradWilsonMSFT

WorkItems are only registered with the concrete WorkItem type, not any interfaces. Try using this instead:

InjectionConstructor
public MyView(ServiceDependency(Type = typeof(WorkItem) IMyWorkItem workItem)
{
workItem.DoAnyThing();
}
Jan 4, 2006 at 12:11 PM
originally posted by: alexsantos

Hi,

My question is if I register one class X that implement interface Y, I can't find the item X using this :

items.FindByType( typeof(Y) ) ???

Your example is not correct for IoC because I need to pass the concrete type and not the "common" type.

If I need to pass ALL concrete type I can't create a modular app.
Jan 5, 2006 at 7:19 AM
originally posted by: BradWilsonMSFT

You can find an item by type like you suggest. This test passes for me:

interface MyInterface { }
class MyConcreteType : MyInterface { }

TestMethod
public void CanFindObjectsInContainerByAnyImplementedType()
{
ManagedObjectCollection<object> collection = CreateManagedObjectCollection();

collection.AddNew<MyConcreteType>();

Assert.AreEqual(1, collection.FindByType<MyInterface>().Count);
}

However, services are a special beast. They are registered under a specific type. In this case, the specific type that the service is registered under is WorkItem. ServiceDependency must search for that specific registered type. If we searched all types implemented by all services, we would: (1) open the door for people to take references to types that the service writer didn't intend, and (2) have to implement a rather complex ambiguity resolution system. We think CAB is best served by registering services with explicit types.

There's nothing stopping you from registering your WorkItem with IMyWorkItem as well (one instance can register itself with as many types as it likes) if you would prefer your code had a service dependency against IMyWorkItem instead.
Jan 6, 2006 at 12:09 PM
originally posted by: alexsantos

I understood....your solution is correct !

I will register the "types" of my workitem.

Thanks,
Alexnaldo Santos