Monday, December 28, 2009

StructureMap – Part 3

This is a continuation of StructureMap – Part 2. We will be getting into adding instances for particular interfaces with StructureMap. I left off last time with the mention of the IMailNotification as a constructor dependency of the INotificationService. So I was trying to figure out how to set different classes to an IMailNotification because I don’t always want to use one. I could have 50 of the things. Basically they’re just messages that are emailed. So let’s get to the code!

Here is the StructureMap code for creating instances:



It reads pretty easy, for requested type IMailNotification add instances of type JoinMailingListNotification with name JoinMailingList and of type ContactNotification with name Contact. I added a little helper class for the DependencyInstanceNames because I love being strongly-typed. My little helper looks like so:

    public class DependencyInstanceNames
public const string JoinMailingList = "JoinMailingList";
public const string Contact = "Contact";

So then…how do you reference this in your code? Guess what? It’s easy too! So in the UI , I simply call:

 var notification = DependencyRegistrar.Resolve<IMailNotification>(DependencyInstanceNames.JoinMailingList);

If you remember from the last post, I said I “stole” the DependencyRegistrar from the sample code in the ASP.NET MVC in Action book. So you can either buy the book or download the sample code from their site. I think I made a few modifications, but nothing major. I know I at least added this method:

public static TInstance With<TWith, TInstance>(TWith o)
return ObjectFactory.With(o).GetInstance<TInstance>();

I added it so I could make this call:

var notificationService = DependencyRegistrar.With<IMailNotification, INotificationService>(notification);

This call is what I was referring to in Part 2, when I said I would talk about it in the next post. If you remember from the Part 2, I had a constructor dependency that looked like this in the StructureMap configure():


Basically what the With call does is lets StructureMap know that I have to pass this into my EmailNotificationService class. Pretty slick stuff I thought. I hope you think the same.

Please let me know if you have any questions or if you see anything that I can improve. Thanks for reading!

kick it on

blog comments powered by Disqus
Related Posts Plugin for WordPress, Blogger...