High Activity

News

  Analyzed 5 days ago based on code collected 6 days ago.
 
Posted about 1 year ago
In a previous post I demonstrated how to wire up HttpControllerContext with Poor Man's DI. In this article I'll show how to wire up HttpControllerContext with Castle Windsor.

This turns out to be remarkably difficult, at least with the ... [More] constraints I tend to set for myself:

Readers of this blog may have an inkling that I have an absolute abhorrence of static state, so anything relying on that is out of the question. In addition to that, I also prefer to leverage the container as much as possible, so I'm not keen on duplicating a responsibility that really belongs to the container. No injecting the container into itself. That's just unnatural and lewd (without being fun). If possible, the solution should be thread-safe. The overall solution should still adhere to the Register Resolve Release pattern, so registering a captured HttpControllerContext is a no-go. It's also unlikely to work, since you'd need to somehow scope each registered instance to its source request. That also rules out nested containers. OK, so given these constraints, how can an object graph like this one be created, only with Castle Windsor instead of Poor Man's DI?

return new CatalogController(    new RouteLinker(        baseUri,        controllerContext));
Somehow, the HttpControllerContext instance must be captured and made available for further resolution of a CatalogController instance.

Capturing the HttpControllerContext

The first step is to capture the HttpControllerContext instance, as early as possible. From my previous post it should be reasonably clear that the best place to capture this instance is from within IHttpControllerActivator.Create.

Here's the requirement: the HttpControllerContext instance must be captured and made available for further resolution of the object graph – preferably in a thread-safe manner. Ideally, it should be captured in a thread-safe object that can start out uninitialized, but then allow exactly one assignment of a value.

At the time I first struggled with this, I was just finishing The Joy of Clojure, so this sounded to me an awful lot like the description of a promise. Crowdsourcing on Twitter turned up that the .NET equivalent of a promise is TaskCompletionSource<T>.

Creating a custom IHttpControllerActivator with an injected TaskCompletionSource<HttpControllerContext> sounds like a good approach. If the custom IHttpControllerActivator can be scoped to a specific request, that would be the solution then and there.

However, as I've previously described, the current incarnation of the ASP.NET Web API has the unfortunate behavior that all framework Services (such as IHttpControllerActivator) are resolved once and cached forever (effectively turning them into having the Singleton lifestyle, despite what you may attempt to configure in your container).

With Dependency Injection, the common solution to bridge the gap between a long-lasting lifestyle and a shorter lifestyle is a factory.

Thus, instead of injecting TaskCompletionSource<HttpControllerContext> into a custom IHttpControllerActivator, a Func<TaskCompletionSource<HttpControllerContext>> can be injected to bridge the lifestyle gap.

One other thing: the custom IHttpControllerActivator is only required to capture the HttpControllerContext for further reference, so I don't want to reimplement all the functionality of DefaultHttpControllerActivator. This is the reason why the custom IHttpControllerActivator ends up being a Decorator:

public class ContextCapturingControllerActivator :    IHttpControllerActivator{    private readonly IHttpControllerActivator activator;    private readonly Func<TaskCompletionSource<HttpControllerContext>>        promiseFactory;     public ContextCapturingControllerActivator(        Func<TaskCompletionSource<HttpControllerContext>> promiseFactory,        IHttpControllerActivator activator)    {        this.activator = activator;        this.promiseFactory = promiseFactory;    }     public IHttpController Create(        HttpControllerContext controllerContext,        Type controllerType)    {        this.promiseFactory().SetResult(controllerContext);        return this.activator.Create(controllerContext, controllerType);    }}
The ContextCapturingControllerActivator class simply Decorates another IHttpControllerActivator and does one thing before delegating the call to the inner implementation: it uses the factory to create a new instance of TaskCompletionSource<HttpControllerContext> and assigns the HttpControllerContext instance to that promise.

Scoping

Because the Web API is basically being an ass (I can write this here, because I'm gambling that the solitary reader making it this far is so desperate that he or she is not going to care about the swearing) by treating framework Services as Singletons, it doesn't matter how it's being registered:

container.Register(Component    .For<IHttpControllerActivator>()    .ImplementedBy<ContextCapturingControllerActivator>());container.Register(Component    .For<IHttpControllerActivator>()    .ImplementedBy<DefaultHttpControllerActivator>());
Notice that because Castle Windsor is being such an awesome library that it implicitly understands the Decorator pattern, I can simple register both Decorator and Decoratee in an ordered sequence.

The factory itself must also be registered as a Singleton (the default in Castle Windsor):

container.Register(Component    .For<Func<TaskCompletionSource<HttpControllerContext>>>()    .AsFactory());
Here, I'm taking advantage of Castle Windsor's Typed Factory Facility, so I'm simply asking it to treat a Func<TaskCompletionSource<HttpControllerContext>> as an Abstract Factory. Doing that means that every time the delegate is being invoked, Castle Windsor will create an instance of TaskCompletionSource<HttpControllerContext> with the correct lifetime.

This provides the bridge from Singleton lifestyle to PerWebRequest:

container.Register(Component    .For<TaskCompletionSource<HttpControllerContext>>()    .LifestylePerWebRequest());
Notice that TaskCompletionSource<HttpControllerContext> is registered with a PerWebRequest lifestyle, which means that every time the above delegate is invoked, it's going to create an instance which is scoped to the current request. This is exactly the desired behavior.

Registering HttpControllerContext

The only thing left is registering the HttpControllerContext class itself:

container.Register(Component    .For<HttpControllerContext>()    .UsingFactoryMethod(k =>         k.Resolve<TaskCompletionSource<HttpControllerContext>>()            .Task.Result)    .LifestylePerWebRequest());
This defines that HttpControllerContext instances are going to be resolved the following way: each time an HttpControllerContext instance is requested, the container is going to look up a TaskCompletionSource<HttpControllerContext> and return the result from that task.

The TaskCompletionSource<HttpControllerContext> instance is scoped per web request and previously captured (as you may recall) by the ContextCapturingControllerActivator class.

That's all (sic!) there's to it :) [Less]
Posted about 1 year ago
Abstract Factory is a tremendously useful pattern when used with Dependency Injection (DI). While I’ve repeatedly described how it can be used to solve various problems in DI, apparently I’ve never described how to implement one. As a comment to ... [More] an older blog post of mine, Thomas Jaskula asks how I’d implement the IOrderShipperFactory.

To stay consistent with the old order shipper scenario, this blog post outlines three alternative ways to implement the IOrderShipperFactory interface.

To make it a bit more challenging, the implementation should create instances of the OrderShipper2 class, which itself has a dependency:

public class OrderShipper2 : IOrderShipper{    private readonly IChannel channel;     public OrderShipper2(IChannel channel)    {        if (channel == null)            throw new ArgumentNullException("channel");         this.channel = channel;    }     public void Ship(Order order)    {        // Ship the order and        // raise a domain event over this.channel    }}
In order to be able to create an instance of OrderShipper2, any factory implementation must be able to supply an IChannel instance.

Manually Coded Factory

The first option is to manually wire up the OrderShipper2 instance within the factory:

public class ManualOrderShipperFactory :    IOrderShipperFactory{    private readonly IChannel channel;     public ManualOrderShipperFactory(IChannel channel)    {        if (channel == null)            throw new ArgumentNullException("channel");         this.channel = channel;    }     public IOrderShipper Create()    {        return new OrderShipper2(this.channel);    }}
This has the advantage that it’s easy to understand. It can be unit tested and implemented in the same library that also contains OrderShipper2 itself. This means that any client of that library is supplied with a read-to-use implementation.

The disadvantage of this approach is that if/when the constructor of OrderShipper2 changes, the ManualOrderShipperFactory class must also be corrected. Pragmatically, this may not be a big deal, but one could successfully argue that this violates the Open/Closed Principle.

Container-based Factory

Another option is to make the implementation a thin Adapter over a DI Container – in this example Castle Windsor:

public class ContainerFactory : IOrderShipperFactory{    private IWindsorContainer container;     public ContainerFactory(IWindsorContainer container)    {        if (container == null)            throw new ArgumentNullException("container");         this.container = container;    }     public IOrderShipper Create()    {        return this.container.Resolve<IOrderShipper>();    }}
But wait! Isn’t this an application of the Service Locator anti-pattern? Not if this class is part of the Composition Root.

If this implementation was placed in the same library as OrderShipper2 itself, it would mean that the library would have a hard dependency on the container. In such a case, it would certainly be a Service Locator.

However, when a Composition Root already references a container, it makes sense to place the ContainerFactory class there. This changes its role to the pure infrastructure component it really ought to be. This seems more SOLID, but the disadvantage is that there’s no longer a ready-to-use implementation packaged together with the LazyOrderShipper2 class. All new clients must supply their own implementation.

Dynamic Proxy

The third option is to basically reduce the principle behind the container-based factory to its core. Why bother writing even a thin Adapter if one can be automatically generated.

With Castle Windsor, the Typed Factory Facility makes this possible:

container.AddFacility<TypedFactoryFacility>();container.Register(Component    .For<IOrderShipperFactory>()    .AsFactory());var factory =    container.Resolve<IOrderShipperFactory>();
There is no longer any code which implements IOrderShipperFactory. Instead, a class conceptually similar to the ContainerFactory class above is dynamically generated and emitted at runtime.

While the code never materializes, conceptually, such a dynamically emitted implementation is still part of the Composition Root.

This approach has the advantage that it’s very DRY, but the disadvantages are similar to the container-based implementation above: there’s no longer a ready-to-use implementation. There’s also the additional disadvantage that out of the three alternative here outlined, the proxy-based implementation is the most difficult to understand. [Less]
Posted about 1 year ago
Picture = thousands of words, right?
Posted about 1 year ago
One of the good things – of a few – of my tenure at the CLR team was being exposed to the metal. One of my interest areas was the loader, PM’ed by one of the most arrogant person I’ve ever met. Fortunately the senior dev in charge of it is an awesome person, and [...]
Posted over 1 year ago by Krzysztof


After successful beta and RC releases final version of Castle Windsor (as well as Castle Core, and a whole set of facilities) has now been released. There are no major changes between final version and RC. The difference is some minor bug ... [More] fixes, improved exception messages and some small improvements all over the place.

 

The packages are available now, on Nuget (with symbols), and via standard .zip download.

 

Last but not least — thank you to everyone who downloaded beta and release candidate and provided feedback. You guys rock. [Less]
Posted over 1 year ago by Krzysztof
Few weeks later than originally expected but here it is – Castle Windsor 3.0 (along with its facilities and Castle.Core) achieved release candidate status.

There is one major new feature in this release: registration API gained ability to ... [More] specify properties to ignore/require. There are some scenarios where that’s useful, for example where integrating with some 3rd party framework that forces you to inherit from a base class which exposes its dependencies as properties. Creating pass-through constructors for each inherited class can be mundane. In those cases you can simply mark those base class properties as required, in which case Windsor will not allow them to be resolved unless all base property dependencies are satisfied. PropertyFilter enum supports several other most common scenarios, and for advanced cases there’s an overload that gives you more control.

Container.Register(
Classes.FromThisAssembly()
.BasedOn<ICommon>()
.Configure(c => c.Properties(PropertyFilter.RequireBase)));

To address performance hit at startup Windsor no longer enables performance counters by default. Now, you have to do it explicitly:

var container = new WindsorContainer();
var diagnostic = LifecycledComponentsReleasePolicy.GetTrackedComponentsDiagnostic(container.Kernel);
var counter = LifecycledComponentsReleasePolicy.GetTrackedComponentsPerformanceCounter(new PerformanceMetricsFactory());
container.Kernel.ReleasePolicy = new LifecycledComponentsReleasePolicy(diagnostic, counter);

Full changelog is included in the packages. Please, if possible, take the time to upgrade to this version and if you find any issues report them so that the final release is rock solid. If no major issues are found, the final release will be published in two weeks.

The binaries are available on Nuget right now, and soon on our website. [Less]
Posted over 1 year ago by nore...@blogger.com (Markus Zywitza)
It has been a long time since my last blog post. It also has been a long time since I worked on the Castle project either. I don’t want to talk about the reasons however, but I had some ideas regarding ActiveRecord which I want to ... [More] share.

My ideas have nothing to do with the current version of Castle ActiveRecord. Mauricio has done a great job pushing an RC out of the door, but AR’s codebase has grown over the years into a state that makes it hard to impossible keeping up with NHibernate’s features.

In the meantime, other changes took place in the world of ORMs that make most AR’s current features obsolete:

For NHibernate there are two independent mapping libraries allowing to work without XML. I have used confORM recently and it is a pleasure to use. Mapping with attributes is rather clumsy compared to confORM, FluentNHibernate, or NHibernate’s own mapping by code. Since NHibernate 2.0 (which is a long time ago), transactions are mandatory. AR uses SessionScope and TransactionScope and a few other scope types which aren’t used widely, making AR even more complicated than naked NHibernate. NHibernate has new mapping features. Honestly, I don’t know whether someone has added them to the AR codebase. The last time I tried, the visitor model used for examining the attributes drove me nuts. Entity Framework has matured and while EF 4.1 is still a bit behind NHibernate, it is simpler to use than ActiveRecord. Goals of ActiveRecord vNext So what are the features I envision for the next AR version? You might guess them from what I don’t like in the current version:

ActiveRecord API (entity.Save() etc.) POCO Support Testability A single Unit-of-Work concept. Abstracting from the used ORM as much as possible reasonable. For now, I will only highlight each of the design goals in short. I will share more on them in separate posts.

ActiveRecord API AR vNext will concentrate on one major goal: Providing an easy to use API of the active record pattern. As a user, I want to call Save() or Find() from anywhere in my code without passing around session objects, DAOs or repositories.

POCO Support The model should consist of plain object classes. The current AR requires inheritance for full support of the active record API. AR vNext will not even contain a base class for models. It will not require to use an attribute either. However, there is a drawback: Even with the full power of C# 4.0, implementing an empty interface is needed to streamline the experience.

Testability Testing without database access is a must for TDD. Even the use of in-memory-databases requires initialization of the ORM which is far more problematic than getting data from an in-process-call to SQLite.

AR vNext will contain the necessary abstractions and native support for mocking and stubbing data access. Have your code use entity.Save() and fail the test if the wrong entity was saved… all without even loading the ORM’s assemblies.

Single Unit-of-Work Concept A unit of work is mandatory unless you want to code demo apps. However, we don’t need separate concepts for web apps, service executables, GUIs and CLI programs. The single UoW must include transactions and allow both implicit and explicit usage.

Reasonable Abstractions You might have noticed that I used ORM in the paragraphs above and not NHibernate. Well, while NH will be used and integrated as default ORM in vNext, I strive to abstract it out of the core API, so that it is possible to plug in other persistence frameworks in the future, which might be EF or RavenDB.

This abstraction will not used at any price. Don’t expect to change a configuration value to move from SQL to NoSQL or something similar. The goal is to factor out ORM-specific features in separate classes, so that you can remove the assembly references and have your compiler tell you what is required to adapt in order to use another ORM.

When can I use it? Right now.

NuGet: Monastry.ActiveRecord-NHibernate

GIT: https://github.com/mzywitza/Monastry.ActiveRecord [Less]
Posted over 1 year ago by Krzysztof
As promised, I released Nuget packages for beta 1 of Windsor 3. This is my first major rollout of Nuget packages, so please report any issues working with them.

Nuget and beta packages
Nuget is quickly evolving and getting more useful ... [More] with each release. However one feature it’s missing right now is support for pre-release packages (this is coming in the next version).

This is not really a big deal, however it means there are a few things you should be aware of.

Recommended version
Since the new package is a pre-release, while I would really like for everyone to start using it immediately and report all issues they find, I quite understand that many people will rather prefer to stick to the last official version for the time being. To accommodate that the new packages are not made recommended versions, so your Nuget explorer will still point to the last stable (2.5.3) version if you search for Windsor, Castle.Core or any other pre-existing package.

 

If you go to command line and install one of the packages without specifying version number, it will install the latest, that is beta 1 version.

SymbolSource.org and debugging into Windsor
Folks at SymbolSource.org added recently support for Nuget (and OpenWrap as well) and the new Castle packages take advantage of that. What it gives you, is you can now easily debug into Windsor’s code, just like .NET framework reference source (there’s a simple guide at SymbolSource on how to do it).

After you’re all set you can step into any of Castle methods in your debugger and watch the magic happen. Very cool thing, even if I say so myself.

 

List of packages
Here’s the full list of v3 beta 1 packages (notice those are not all Castle packages, just those that were published as v3 beta 1 rollout of Windsor):

Castle.Core – Contains Castle.Core.dll which includes DynamicProxy, DictionaryAdapter, EmailSender, logging abstractions and some other goodies.
Castle.Core-log4net – Contains Castle.Services.Logging.Log4netIntegration.dll, that is implementation of Castle logging abstractions for log4net
Castle.Core-NLog – Contains Castle.Services.Logging.NLogIntegration.dll, that is implementation of Castle logging abstractions for NLog
Castle.Windsor – Contains Castle.Windsor.dll which has Windsor itself and two most commonly used facilities – Typed Factory facility and Startable facility.
Castle.LoggingFacility – Contains logging facility.
Castle.Windsor-log4net – Empty package that just installs logging facility and Castle.Core-log4net (and their dependencies obviously).
Castle.Windsor-NLog – Empty package that just installs logging facility and Castle.CoreNLog (and their dependencies obviously).
Castle.WcfIntegrationFacility – Windsor’s WCF facility.
Castle.SynchronizeFacility – Windsor’s Synchronize facility.
Castle.RemotingFacility – Windsor’s Remoting facility (extracted out of Castle.Windsor.dll)
Castle.EventWiringFacility – Windsor’s Event Wiring facility (extracted out of Castle.Windsor.dll)
Castle.FactorySupportFacility– Windsor’s Factory Support facility (extracted out of Castle.Windsor.dll)

 

I hope this will make it easier for everyone to test drive Windsor. And if you find any issues, have any suggestions or ideas, do not hesitate to bring them up, either on our google group, or issue tracker. [Less]
Posted over 1 year ago
I’ve applications that can work in two distinct configuration, they are based on WPF and MVVM, where the VM communicates with the Domain / Business Logic through services like IXxxxService. All View Models depends from one or more services and thanks to Castle I can decide with configuration file which concrete class to use for [...]
Posted almost 2 years ago
It’s been too long since I posted since .NET code, and I’ve been itching to.  (Actually, I really want to write more about politics, but I figured if I don’t show some code soon, I’m gonna lost my techy audience)  Fortunately, I’ve got a ... [More] backlog of things I’ve been meaning to write about.  Today’s is the PropertyBagTextWriter.

The original purpose of this for a particular use in combination with Castle Monorail and Linq-2-Sql, but it has been made general purpose, so you may find a use for it in other environments. 

Now, when Linq-2-Sql was still in beta, the DataContext object had a property which held, as a string, the SQL generated from the Linq query.  As I was writing a Monorail website, I often assigned that property to a value in the PorpertyBag (which is just a IDictionary, not even a IDictionary<K,V>  -- PropertyBag[“SQL”] = db.Log;), and write it in  an HTML comment on the webpage, so I could see I was getting what I expected.  However, the designer eventually realized that a string property wasn’t good enough, as the Linq query could produce several SQL statement, some of which would be based on the response from the earlier ones.  So, they replaced it with a property which can be set to a TextWriter and have the SQL output written there.  So, to use it the way I was before, I needed a TextWriter-ish object, which would set it’s output to a value in a Dictionary  (db.Log = new PropertyBagTextWriter(“SQL”, PropertyBag); )   The important point here is that it’s self-contained.  Once we set the property to the PropertyBagTextWriter object,  we should never have to interact with it again.  The value should just appear in the dictionary when it’s ready.

The code itself is fairly straightforward.  Start by deriving a new class from StringWriter, which is usually the best way to create a customized TextWriter.  That way, it’s handle the details of gathering and formatting the data from the stream, and all we have to deal with is the string at the end.

class ProperyBagTextWriter : StringWriter
{

Next, we’re going to need to know the dictionary the output will be stored in,  and the key, so we accept those in the constructor, and hold on to them for later:

public ProperyBagTextWriter(string key, IDictionary bag)
{
this.key = key;
this.bag = bag;
}
string key;
IDictionary bag;

Then the key point:   When we get a Flush() call, we save the text we gathered so far into the dictionary under that key:

public override void Flush()
{
base.Flush();
bag[key] = base.ToString();
}

However, since we can’t count on the Flush always being called when we need it, we’ll force a flush at other times, like during the Dispose() and after writing a line:

protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
Flush();
}

public override void Write(char[] buffer, int index, int count)
{
base.Write(buffer, index, count);
Flush();
}

 

That all there is to it.  Besides the Linq2Sql log, I’ve also used it for the output from a XSLT transformation.

 

Source Code: I’ve decided to get with the times, and create (well, actually “use”… I created it a while ago), a GitHub account.  So, you can find this class, code from my future posts, and when I get around to it, code from my older post, at http://github.com/jamescurran/HonestIllusion

Share this post: Email it! | bookmark it! | digg it! | reddit! [Less]
 

 
 

Creative Commons License Copyright © 2013 Black Duck Software, Inc. and its contributors, Some Rights Reserved. Unless otherwise marked, this work is licensed under a Creative Commons Attribution 3.0 Unported License . Ohloh ® and the Ohloh logo are trademarks of Black Duck Software, Inc. in the United States and/or other jurisdictions. All other trademarks are the property of their respective holders.