Created
July 22, 2010 21:20
-
-
Save BenHall/486603 to your computer and use it in GitHub Desktop.
Castle Dictionary Adapter Example
This file contains hidden or 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
using System; | |
using System.Configuration; | |
using Castle.Components.DictionaryAdapter; | |
using Castle.MicroKernel.Registration; | |
using Castle.Windsor; | |
using Rhino.Mocks; | |
namespace CastleDictionaryAdapterExample | |
{ | |
class Program | |
{ | |
static void Main() | |
{ | |
new DictionaryAdapterFactory().GetAdapter<IApplicationConfiguration>(ConfigurationManager.AppSettings); | |
WindsorContainer container = new WindsorContainer(); | |
container.AddFacility<Castle.Facilities.FactorySupport.FactorySupportFacility>(); | |
container.Register( | |
Component.For<IApplicationConfiguration>().UsingFactoryMethod( | |
() => new DictionaryAdapterFactory().GetAdapter<IApplicationConfiguration>(ConfigurationManager.AppSettings))); | |
var configuration = container.Resolve<IApplicationConfiguration>(); | |
Console.WriteLine(configuration.EnableNewsletterSignup); | |
var stubConfig = MockRepository.GenerateStub<IApplicationConfiguration>(); | |
stubConfig.EnableNewsletterSignup = true; | |
Console.WriteLine(stubConfig.EnableNewsletterSignup); | |
Console.ReadLine(); | |
} | |
} | |
class NewsletterSignupService | |
{ | |
public bool Signup(string email) | |
{ | |
if (!Boolean.Parse(ConfigurationManager.AppSettings["EnableNewsletterSignup"])) | |
return false; | |
return true; // technically this would go off to an external web service | |
} | |
} | |
class NewsletterSignupServiceWithoutAppConfigDependency | |
{ | |
private readonly IApplicationConfiguration _configuration; | |
public NewsletterSignupServiceWithoutAppConfigDependency(IApplicationConfiguration configuration) | |
{ | |
_configuration = configuration; | |
} | |
public bool Signup(string email) | |
{ | |
if (!_configuration.EnableNewsletterSignup) | |
return false; | |
return true; // technically this would go off to an external web service | |
} | |
} | |
public interface IApplicationConfiguration | |
{ | |
bool EnableNewsletterSignup { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the blog post and the gist. I have posted an expanded/updated version of it.