Created
November 21, 2010 17:25
-
-
Save darrencauthon/708929 to your computer and use it in GitHub Desktop.
This is a short example showing how one can use a separate class to determine which class should be used in which context.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CatalogContextDeterminer | |
{ | |
private XPrincipal principal; | |
public CatalogContextDeterminer(XPrincipal principal) | |
{ | |
principal = principal; | |
} | |
public Type GetCatalogContextType() | |
{ | |
if (TheUserIsNotLoggedIn()) | |
return typeof (NonMemberCatalogContext); | |
var memberType = GetTheCurrentUsersMemberType(); | |
if (ThisIsAChapterMember(memberType)) | |
return GetTheChapterPricingForThisMemberType(memberType); | |
else | |
return typeof (MemberCatalogContext); | |
} | |
// .. more here | |
} | |
public class CatalogContextRegistration : IServiceRegistration | |
{ | |
public void Register(IServiceLocator locator) | |
{ | |
locator.Register(() => | |
{ | |
var determiner = locator.Resolve<CatalogContextDeterminer>(); | |
return locator.Resolve(determiner.GetCatalogContextType()) as ICatalogContext; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
BTW, one more point:
This class got more complex later. Client came back and wanted different pricing than chapter or member, and then had special pricing considerations based on if you were creating an account versus if you were creating an order as a guest. All of that complexity and change stayed in one place.
I know this isn't the best example of an alternative to "CanProcess()," this is just the freshest example of using this pattern in my head. But it works for other situations, too, even those where multiple classes needed to be instantiated and called.
It's really nice to be able to ask the container, "Resolve the implementation for this interface" or "Resolve all implementations of this interface" and know that whatever you get back is relevant to your situation.