public interface IProcessor<T> { void Process(T instance); } foreach(AbstractType instance in myClass.SomeCollection) OnProcess(instance); public void OnProcess<T>(T instance) { IProcessor<T> processor = unityContainer.Resolve<IProcessor<T>>(); processor.Process(instance); }
The problem with this code is that the in OnProcess is always AbstractType, and not the concrete type of the instance being passed. I currently see two possibilities.
01: Create a non generic IProcessor and use it as the base for IProcessor. Any implementor will have to implement both generic and non-generic Process methods, typically typecasting and passing onto the generic method.
02: Use Type.MakeGenericType to get the IProcessor, resolve that, and then use reflection to invoke the Process method.
Both of these approaches feel a bit ‘unclean’. Can anyone think of a way I can do this without having to resort to these practices?
Thanks
Pete
2 will be a performance killer (the necessary dynamic/relection invoke in particular is slow)
1 is a common answer to this problem, especially with explicit implementation; the problem is getting hold of the type… does unity allow query with a
Typeinstance, rather than via generics? If so something like below… of course, you might still have to useMakeGenericType:Where
instanceTypeis perhaps viainstance.GetType(). For similar reasons, it might be helpful to expose theTas aTypeon theIProcessor:Of course, an (optional) base-class might allow you to avoid some of this per-implementation: