Getting all services that Implement a particular interface (derived from IDependency or not)

Topics: Writing modules
May 21, 2012 at 10:27 AM
Edited May 21, 2012 at 10:35 AM

Wasn't sure the best way to phrase the question, but essentially, what i want to so is define an interface such as 


public interface IWhatsMyName
{     
    string GetMyName();
}


Then I want two or more services to implement this interface

public class HiMyNameIsA: IWhatsMyName
{   
     public string GetMyName(){ return "Slim Shady"; }

public class HiMyNameIsB: IWhatsMyName
{   
     public string GetMyName(){ return "Marshal Mathers"; }

public class WhatsMyMFName: IWhatsMyName
{   

     public string GetMyName(){ return "Snoop"; }




Then in some other service I want to say something like


//find all implementors of the IWhatsMyName inteface
foreach(IWhatsMyName service in ?)
{    
     Output.WriteLine( service.GetMyName() ); 
}



Which should yield...


Slim Shady
Marshal Mathers
Snoop


How can this be done?
Any help is appreciated. Thanks.
R.
















Developer
May 21, 2012 at 10:58 AM
Edited May 21, 2012 at 11:00 AM

If you derive from IDependency you get such functionality for free: requesting

 

IEnumerable<IMyDependeny>

 

in the ctor gives you all instances which you can loop over then.

You could also derive your interfaces from IEventHandler. This is something special, with it you could request simply IMyDependency in the ctor, but when you call its methods actually that method of all registered IMyDependency types is called. You can only have void methods this way, though. Event handlers are more than that, they also make it possible to call into the interface without having a static dependency on the type, but that's another story. See this and this.

May 21, 2012 at 11:33 AM

That's beautiful. Thanks.  

I had thought about using IEventHandler but really need to use the Interface to return results. In my example in the original question I return a string but in fact I will want to return a IEnumerable of objects from each service and then aggregate the results....

interface IMessageFeedSource
{
    IEnumerable<IMessageFeedObject> GetNewEvents(DateTime startDate, DateTime endDate)

I think I'm going to try out

IEnumerable<IMessageFeedObject>

and see how it works!

Thanks for the quick response :)

Ryan