268
I Use This!
Very Low Activity

News

Analyzed about 11 hours ago. based on code collected 1 day ago.
Posted over 13 years ago
I've been spending more and more time thinking about how we over-engineer solutions and even libraries. Currently my feeling is that NuGet and OpenWrap are only going to make this problem worse and not better. The basic problem with buy versus build ... [More] is that it's posing the wrong choice. Of course buy is cheaper than build. But it's like trying to chose between sparkling and still: the correct answer is tap. A number of years ago I built a system that used Binsor for configuration. Here were the benefits (to me): Concise syntax Programmable Environmental Deltas Of these, the first is nice to have, but not essential, the second is vital but can be achieved with the fluent configuration API. It was only the third that Binsor offered that no other solution had. Here were the costs: Utterly undocumented. Figuring out how to use a new facility was an exercise in hitting Google until it worked. No-one else could understand it other than me. It prevented me from using Windsor features it didn't support. The build and upgrade story was an absolute nightmare. It took someone else to point out that, actually, Binsor was horribly over-engineered for what I actually needed. Once I'd twigged to this, I realized that it was actually perfectly possible to knock together an alternative. One that I could easily use to migrate away from Binsor while keeping the features I needed. I did it in Ruby because, well, I like Ruby. And I called it Dusty because I used to watch Ted Rogers when I was a kid. Technical Details So, it's now up as a gist. It's in three parts. The main part, dusty.rb is the main code and an example of how to configure it. The examples are taken from real live running code, but are incomplete. The delta file is a full valid environmental delta file. The dusty.cs file just gives the two functions you need to call it. Ideally, you wouldn't even need IronRuby for this. However, it does make the configuration syntax nicer at the cost of some initial setup. The configuration syntax, as you can see, is deliberately close to Binsor's, precisely because I was using it to enable a migration away from Binsor. You'll note that the only reuse method this supports is Joe Walnes' favourite technique. If you need the container, you can just access it directly. If you need a new feature, just change the code. And if you don't need it, don't use it. Technorati Tags: Castle Windsor,Binsor [Less]
Posted over 13 years ago by José
This is a basic example of ISubDependencyResolver for Castle Windsor. Given the following service: public class MySuperService { public MySuperService(string connectionString) { //.. } } I want Windsor automatically to look at the web.config or ... [More] app.config settings and if there is a configuration with key equals to the parameter name (i.e. “connectionString”) to inject automatically the value when constructing MySuperService instance. The infrastructure code is this: public class DependenciesFromAppSettings : AbstractFacility { protected override void Init() { var dic = ConfigurationManager .AppSettings .AllKeys .ToDictionary(k => k, k => ConfigurationManager.AppSettings[k]); Kernel.Resolver.AddSubResolver(new DependenciesFromAppSettingsResolver(dic)); } } public class DependenciesFromAppSettingsResolver : ISubDependencyResolver { private readonly IDictionary<string, string> webConfig; public DependenciesFromAppSettingsResolver(IDictionary<string, string> webConfig) { this.webConfig = webConfig; } public object Resolve( CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency) { return webConfig[dependency.DependencyKey]; } public bool CanResolve( CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency) { return dependency.DependencyType == DependencyType.Parameter && webConfig.ContainsKey(dependency.DependencyKey); } } And the usage is very straightforward: [TestFixture] public class DependenciesFromAppSettingsTests { [Test] public void CanInjectSettingsFromAppConfig() { var container = new WindsorContainer(); container.AddFacility<DependenciesFromAppSettings>(); container.Register(Component.For<MySuperService>()); var superInstance = container.Resolve<MySuperService>(); superInstance.ConnectionString .Should().Be.EqualTo("sample conn string"); } } http://feeds.feedburner.com/JoseFRomaniello [Less]
Posted over 13 years ago by [email protected] (bling)
I was debating whether to make this blog post because it’s so damn simple to implement, but hey, if it saves someone else time, I did some good. First of all, register an ILazyComponentLoader into Windsor:var c = new WindsorContainer(); ... [More] c.Register(Component.For<LazyComponentAutoMocker>()); Then, the implementation of LazyComponentAutoMocker is simply this:public class LazyComponentAutoMocker : ILazyComponentLoader { public IRegistration Load(string key, Type service, IDictionary arguments) { return Component.For(service).Instance(Substitute.For(new[] { service }, null)); } } And you’re done!  Here’s a simple unit test example using only the code from above:[Test] public void IDictionary_Add_Invoked() { var dict = c.Resolve<IDictionary>(); dict.Add(1, 1); dict.Received().Add(1, 1); } That was almost too easy. [Less]
Posted over 13 years ago
I use AutoMockingContainer extensively in my test projects, and I ‘ve build over time an automocking container that satisfy all of my needs. Thanks to Castle Windsor, using complex logic with the AutomockingContainer is a breeze. Suppose you have ... [More] this ViewModel Figure 1: ViewModel under test The only aspect I’m interested in is the SelectedLinkResult [...] [Less]
Posted over 13 years ago by Krzysztof
This is a follow up to my previous post. If you haven’t yet – go and read that one first. I’ll wait. So where were we? Aha… In the last post I said, that Windsor (any container in general) creates objects for you, hence it owns them, ergo its ... [More] responsibility is to properly end their lifetime when they’re no longer needed. Since as I mentioned in my previous post, Windsor will track your component, it’s a common misconception held by users that in order to properly release all components they must call Release method on the container. container.Release(myComponent); How will Windsor know I no longer need an object? That’s the most important part of this post really, so pay attention. In Windsor (every container in general) every component has a lifestyle associated with it. In short lifestyle defines the context in which an instance should be reused. If you want to have just single instance of a component in the context of the container, you give the object a singleton lifestyle (which is the default in Windsor). If you want to reuse your object in the context of a web request, you give it a lifestyle of a per-web-request and so on. Now the word context (though overloaded) is important here. When the context ends? While some contexts, like web request have a well defined ends that Windsor can detect, that’s not the case for every of them. This brings us to the Release method. Windsor has a Release method that you use to explicitly tell it “hey, I’m not gonna use this this object anymore.” Although the method is named very imperatively, which would suggest it takes immediate action, it’s not often the case. Quite a lot of time may pass between you call the method and Windsor will get the object destroyed. When the object gets really destroyed is up to its lifestyle manager, and they act differently. Singleton will ignore your call to Release because the instance is global in the scope of the container that created it, and the fact that you don’t need the object in one place does not mean you won’t need it moments later somewhere else. The scope of the singleton lifestyle has a well defined end. Windsor will destroy the singletons when the container itself is being disposed. This also means that you don’t have to Release your singletons – disposing of the container will take care of that. Per-web-request will ignore your call to Release for similar reasons – the object is global in the scope of a web-request. Web request also has a well defined end, so it will wait with destroying the object till the end of the web request and then do all the work necessary. This also means that you don’t have to release your per-web-request components – Windsor can detect end of a web request and release the per-web-request components without and intervention from your side. Per-thread is like singleton in the scope of a thread. Releasing Per-thread components does nothing, they will be released when the container is disposed. This means that in this case as well you don’t have to do anything explicitly about them (except for remembering to dispose the container obviously) .. Pooled components are different. They don’t really have a well defined “end” so you need to return a component to the pool explicitly (that is pass them to container’s Release method), and Windsor (depending on the component and configuration of the pool) may either return the object to the pool, recycle it, or destroy and let it go. Thing is – it matters, and it usually makes sense to return the object to the pool, as soon as possible (think connection pooling in ADO.NET). Transient components are similar to pooled, because there’s no well known end to transient component’s lifetime, and Windsor will not know if you still want to use a component or not, unless you explicitly tell it (by calling Release). Since transient components are by definition non-shared Windsor will immediately destroy the component when you Release it. And then it gets interesting If you’re now scratching your head thinking “Does Windsor really puts all the burden of releasing stuff on me?” don’t despair. The reality is – you never have to call Release explicitly in your application code. Here’s why. You never have to call Release… Releasing a component releases entire graph. As outlined in previous section, Windsor can detect end of scope for components with most lifetimes. In that case, if you have a per-web-request ShoppingCard component that depends on transient PaymentCalculationService and singleton AuditWriter, when the request ends Windsor will release the shopping card along with both of its dependencies. Since auditwriter is a singleton releasing it will not have any effect (which is what we want) but the transient payment calculator will be releases without you having to do anything explicitly. You obviously need to structure your application properly for this to work. If you’re abusing the container as service locator than you’re cutting a branch you’re sitting on. Explicitly… This also works with typed factories – when a factory is released, all the components that you pulled via the factory will be released as well. However you need to be cautious here – if you’re expecting to be pulling many components during factory’s lifetime (especially if the factory is a singleton) you may end up needlessly holding on to the components for much too long, causing a memory leak. Imagine you’re writing a web browser, and you have a TabFactory, that creates tabs to display in your browser. The factory would be a singleton in your application, but the tabs it produces would be transient – user can open many tabs, then close them, then open some more, and close them as well. Being a web savvy person you probably know firsthand how quickly memory consumption in a web browser can go up so you certainly don’t want to wait until you dispose of your container to release the factory and release all the tabs it ever created, even the ones that were closed days ago. More likely you’d want to tell Windsor to release your transient tabs as soon as the user closes it. Easy – just make sure your TabFactory has a releasing method that you call when the tab is closed. The important piece here is that you’d be calling a method on a factory interface that is part of your application code, not method on the container (well – ultimately that will be the result, but you don’t do this explicitly). UPDATE: As Mark pointed out in the comment there are certain low level components that act as factories for the root object in our application (IControllerFactory in MVC, IInstanceProvider in WCF etc). If you’re not using typed factories to provide these service and implement them manually pulling stuff from the container, than the other rule (discussed below) applies – release anything you explicitly resolve In your application code There are places where you do need to call Release explicitly – in code that extends or modifies the container. For example if you’re using a factory method to create a component by resolving another component first, you should release the other component. container.Register( Component.For<ITaxCalculator>() .UsingFactoryMethod(k => { var country = k.Resolve<ICountry>(user.CountryCode); var taxCalculator = country.GetTaxCalculator(); k.ReleaseComponent(country); return taxCalculator; }) ); This is a code you could place in one of your installers. It is completely artificial but that’s not the point. Point is, we’re using a factory method to provide instances of a component (tax calculator) and for this we’re using another component (country). Remember the rule – You have to release anything you explicitly resolve. We did resolve the country, so unless we are sure that the country is and always will be a singleton or have one of the other self-releasing lifestyles, we should release it before returning the tax calculator. [Less]
Posted over 13 years ago by [email protected] (mausch)
I see many questions on Stackoverflow that are basically variants of this: "How can I integrate my custom MembershipProvider into my IoC container?" Integrating your custom MembershipProvider to a IoC container has many advantages, since it would let ... [More] you treat it just like any other service: you could manage its lifetime, dependencies, configuration, even proxy it if you wanted. Problem is, MembershipProviders are one of those things that are managed by the ASP.NET runtime. You just configure it in your web.config and the runtime instantiates it when it's needed. You don't really get much control over its creation. A cheap solution is to use the container as a service locator directly in your membership provider (using something like CommonServiceLocator), e.g.: public class MyMembershipProvider : MembershipProvider { private IUserRepository repo { get { return ServiceLocator.Current.GetInstance<IUserRepository>(); } } public override string GetUserNameByEmail(string email) { return repo.First(u => u.Email == email); } ... } Using a service locator like this should be avoided as much as possible. Mark Seeman explains it thoroughly in this article. In a nutshell, you want to limit the usage of the service locator pattern to glue code (i.e. very low-level infrastracture), even there use it as little as possible, and never use it in application-level code. As usual with this kind of problems, the solution is to write a wrapper/adapter/bridge/whatever-you-want-to-call-it that isolates the issue so that client code doesn't have to suffer it. It's similar in concept to the implementation of Windsor-managed HttpModules. It's actually simpler than that, we don't need a custom lifestyle manager here. In fact, Spring.NET has had such an adapter for quite some time. The only problem with that implementation is that you can't change the lifetime of the custom provider, it's always a singleton. My implementation doesn't have this limitation: your provider can be transient, singleton, per web request, whatever. The price for this is that you can't use Initialize() (more precisely, it won't do anything), but since it's managed by the container, you can use the container to provide any configuration, which is much more flexible. The implementation is about 200 lines of boring, simple code so I'm not going to post it here. It does use Windsor as a service locator, but this is low-level infrastracture/glue code. The goal here is to keep your code clean. The code is here, and here's how to use it: Write your custom MembershipProvider as a regular component, using constructor or property injection as you see fit. Implement IContainerAccessor in your global HttpApplication class. Use this article as reference. Register your custom provider in Windsor and assign a name to the component. E.g.: container.Register(Component.For<MyMembershipProvider>() .LifeStyle.Transient .Named("myProvider")); Register your custom provider in your web.config using the adapter and referencing the name of the corresponding Windsor component in a "providerId" attribute. E.g.: <membership defaultProvider="customProvider"> <providers> <clear/> <add name="customProvider" type="ProviderInjection.WebWindsorMembershipProvider, ProviderInjection" providerId="myProvider"/> </providers> </membership> That's it. Here's a sample app that you can use as reference. This can be easily ported to any IoC container, and for any provider like RoleProvider, ProfileProvider, etc. I haven't used this in anger so let me know if you have any problems with it. [Less]
Posted over 13 years ago
Today we released second bugfix release for Windsor 2.5 and for Core 2.5 (incl. DynamicProxy, which is what probably is the most interesting to people). This time there are no new features, only fixes to issues identified since the last release (you ... [More] can see the entire list in changes.txt). We have however updated to NLog 2, and since it works in Silverlight, this release also has Logging Facility for Silverlight. This is very likely the last release in 2.5 branch, and all development now moves to vNext. One thing you may notice, is that while file number was bumped to 2.5.2, assembly version still shows 2.5.1. This was requested by several users who didn’t want to have to recompile all third party dependencies using Windsor 2.5.1 again, in order to use the new version. If you’re in such situation, you may drop and replace older assemblies with the new ones, and in 99% of cases you should be just fine. However in order to fix some issues, there were few breaking changes, so if the other projects you’re using were depending on the changed code you will have to upgrade them to version compatible with Windsor 2.5.2 anyway. New logo One more noteworthy development in Castle land, as you may have noticed if you visited Castle Project website recently is that we have a new logo (or rather – set of logos) created by my very talented wife. Now back to me – the downloads are here (Windsor and Core) and here (just Core) – enjoy. I am on a horse. [Less]
Posted over 13 years ago by Krzysztof
Today we released second bugfix release for Windsor 2.5 and for Core 2.5 (incl. DynamicProxy, which is what probably is the most interesting to people). This time there are no new features, only fixes to issues identified since the last release ... [More] (you can see the entire list in changes.txt). We have however updated to NLog 2, and since it works in Silverlight, this release also has Logging Facility for Silverlight. This is very likely the last release in 2.5 branch, and all development now moves to vNext. One thing you may notice, is that while file number was bumped to 2.5.2, assembly version still shows 2.5.1. This was requested by several users who didn’t want to have to recompile all third party dependencies using Windsor 2.5.1 again, in order to use the new version. If you’re in such situation, you may drop and replace older assemblies with the new ones, and in 99% of cases you should be just fine. However in order to fix some issues, there were few breaking changes, so if the other projects you’re using were depending on the changed code you will have to upgrade them to version compatible with Windsor 2.5.2 anyway. New logo One more noteworthy development in Castle land, as you may have noticed if you visited Castle Project website recently is that we have a new logo (or rather – set of logos) created by my very talented wife. Now back to me – the downloads are here (Windsor and Core) and here (just Core) – enjoy. I am on a horse. [Less]
Posted over 13 years ago by [email protected] (Mike Hadlow)
I’m putting together a new project, TardisBank.com, using RavenDb, ASP.NET MVC and Windsor. It’s up on github here: http://github.com/mikehadlow/Suteki.TardisBank Here’s how I wire up Windsor and RavenDb. First, in Global.asax.cs I initialise the ... [More] container and ask it to load and run installers from all the application assemblies: public class MvcApplication : System.Web.HttpApplication, IContainerAccessor { ... protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); InitialiseContainer(); InitialiseControllerFactory(); } protected void InitialiseContainer() { if (container == null) { container = new WindsorContainer() .Install( FromAssembly.InDirectory(new AssemblyFilter(HttpRuntime.BinDirectory, "Suteki.*.dll"))); } } protected void InitialiseControllerFactory() { var controllerFactory = container.Resolve<IControllerFactory>(); ControllerBuilder.Current.SetControllerFactory(controllerFactory); } static IWindsorContainer container; public IWindsorContainer Container { get { return container; } } } One of the installers it runs is my RavenInstaller: public class RavenInstaller : IWindsorInstaller { public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register( Component.For<IDocumentStore>().Instance(CreateDocumentStore()).LifeStyle.Singleton, Component.For<IDocumentSession>().UsingFactoryMethod(GetDocumentSesssion).LifeStyle.PerWebRequest ); } static IDocumentStore CreateDocumentStore() { var store = new DocumentStore { ConnectionStringName = "tardisConnection" }; store.Initialize(); return store; } static IDocumentSession GetDocumentSesssion(IKernel kernel) { var store = kernel.Resolve<IDocumentStore>(); return store.OpenSession(); } } Because Windsor already provides a global application store for both singleton and per-request components, we can give it the responsibility of handling the instantiation and lifecycle of the DocumentStore and DocumentSesssion. The DocumentStore is created and initialised once the first time it is requested. The DocumentSession has a PerWebRequest lifestyle and is created using a factory method the first time it is requested. Don’t forget to register the PerRequestLifestyleModule in Web.config: <system.webServer> <validation validateIntegratedModeConfiguration="false"/> <modules runAllManagedModulesForAllRequests="true"> <add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.Windsor" /> </modules> </system.webServer> Windsor will properly dispose both the DocumentStore when the application closes and the DocumentSession at the end of each request. [Less]
Posted over 13 years ago
The subject of Dependency Injection (DI) in general, and DI Containers specifically, suffers from horrible terminology that seems to confuse a lot of people. Newcomers to DI often think about DI Containers as a sort of Abstract Factory on steroids. ... [More] It’s not. Nicholas Blumhardt already realized and described this phenomenon a couple of years ago. The core of the matter is that as developers, we are extremely accustomed to thinking about components and services in terms of queries instead of commands. However, the Hollywood Principle insists that we should embrace a tell, don’t ask philosophy. We can apply this principles to DI Containers as well: Don’t call the container; it’l call you. This leads us to what Krzysztof Koźmic calls the three calls pattern. Basically it states that we should only do three things with a DI Container: Bootstrap the container Resolve root components Dispose this container This is very sound advice and independently of Krzysztof I’ve been doing something similar for years – so perhaps the pattern label is actually in order here. However, I think that the pattern deserves a more catchy name, so in the spirit of the Arrange Act Assert (AAA) pattern for unit testing I propose that we name it the Register Resolve Release (RRR) pattern. The names originate with Castle Windsor terminology, where we: Register components with the container Resolve root components Release components from the container Other containers also support the RRR pattern, but if we were to pick their terminology, it would rather be the Configure GetInstance Dispose (CGD) pattern (or something similar), and that’s just not as catchy. We can rewrite a previous example with Castle Windsor and annotate it with comments to call out where the three container phases occur: private static void Main(string[] args){    var container = new WindsorContainer();    container.Kernel.Resolver.AddSubResolver(        new CollectionResolver(container.Kernel));     // Register    container.Register(        Component.For<IParser>()            .ImplementedBy<WineInformationParser>(),        Component.For<IParser>()            .ImplementedBy<HelpParser>(),        Component.For<IParseService>()            .ImplementedBy<CoalescingParserSelector>(),        Component.For<IWineRepository>()            .ImplementedBy<SqlWineRepository>(),        Component.For<IMessageWriter>()            .ImplementedBy<ConsoleMessageWriter>());     // Resolve    var ps = container.Resolve<IParseService>();    ps.Parse(args).CreateCommand().Execute();     // Release    container.Release(ps);    container.Dispose();} Notice that in most cases, explicitly invoking the Release method isn’t necessary, but I included it here to make the pattern stand out. So there it is: the Register Resolve Release pattern. [Less]