Friday, November 7, 2008

LinFu.DynamicProxy 1.01 is now a part of NHibernate!

After passing all 1500+ tests in the NHibernate test suite, LinFu.DP1 will now be an official part of the NHibernate distribution!

It's really an honor to be a part of a project that is so well-known in the .NET community, and I really want to thank the NHibernate team for giving LinFu a chance.

There were a lot of developers who shied away from LinFu DP1 for the lack of unit tests, and this proves that LinFu DP 1.0 works as advertised, regardless of whether or not the tests existed. You now have 1500+ reasons to try it out without worrying about any problems, so give it a shot, and I'll always be here to answer your questions if anything breaks.

[Disclaimer: That being said, I'm now a TDD convert and I no longer develop anything without a battery of automated unit tests--but it's still an big ego-booster to know that your code works exactly as it's supposed to work :) ]

Monday, September 22, 2008

LinFu IoC 2.0 Reaches an Important Milestone

Making the Grade

After nearly two months of hard work, I am pleased to announce the impending release of LinFu.IoC v2.0! Today marks an amazing milestone in the development of LinFu's new IoC container because as of the latest build (revision 258), LinFu is the first IoC container framework to pass ALL tests in both the "MustHave" and the "ShouldHave" categories in the latest comparison between the following IoC Frameworks:

  • AutoFac
  • Castle
  • LinFu
  • Ninject
  • StructureMap
  • Spring.NET
  • Unity
The feature lists might vary among these IoC frameworks, but Andrey's blog post does a great job of listing some of the features that an Inversion of Control container "must" have, in addition to the features that it "should" have", and I am proud to say that LinFu is the first IoC container to successfully implement every feature described in that blog post!

What this means is that LinFu.IoC (formerly Simple.IoC) has gone from an undocumented and untested inversion of control container to a fully documented, heavily tested, feature-laden container that is capable of performing all of the tasks that one would expect from a commercial-grade inversion of control container.

In addition to the keeping the code as clean and as compact as possible, I spent countless hours ensuring that every single method, class, interface, property and enum is fully documented, regardless of whether or not that item was marked as public, internal, or private. I love my code and I love what I do, and I hope that shows in the code that I write.

The best part about all this is that LinFu's IoC container framework weighs in at only 94KB, making it the smallest IoC framework among its brethen, with the Autofac container falling at a close 110KB.

Within the next few weeks, I'll be publishing an article on CodeProject that details all the features that you can expect from LinFu.IoC 2.0, and I will time the release so that it coincides with the actual CodeProject article itself.

Meanwhile, stay tuned!

EDIT: I realize that this post is quite scant on details so if you want to dive straight into the LinFu.IoC source, you can just go here. If you want to take a look at the IoC framework comparison project, click here. The code practically speaks for itself. Enjoy!

Monday, August 4, 2008

Making Simple.IoC Even More Simple

Believe it or not, the following code represents most of LinFu.IoC's functionality when managing service instances:

// The SimpleContainer will handle unnamed services
public class SimpleContainer : IContainer
private readonly Dictionary _factories = new Dictionary();

public virtual bool SuppressErrors
get; set;

public virtual void AddFactory(Type serviceType, IFactory factory)
_factories[serviceType] = factory;

public virtual bool Contains(Type serviceType)
return _factories.ContainsKey(serviceType);

public virtual object GetService(Type serviceType)
object result = null;
if (!_factories.ContainsKey(serviceType) && !SuppressErrors)
throw new ServiceNotFoundException(serviceType);

if (!_factories.ContainsKey(serviceType) && SuppressErrors)
return null;

// Use the corresponding factory
// and create the service instance
var factory = _factories[serviceType];
if (factory != null)
result = factory.CreateInstance(this);

return result;

// The named container will handle named services
public class NamedContainer : SimpleContainer, INamedContainer
protected readonly Dictionary> _namedFactories =
new Dictionary>();

public virtual void AddFactory(string serviceName, Type serviceType, IFactory factory)
if (serviceName == string.Empty)
AddFactory(serviceType, factory);
// Create the entry, if necessary
if (!_namedFactories.ContainsKey(serviceName))
_namedFactories[serviceName] = new Dictionary();

_namedFactories[serviceName][serviceType] = factory;

public virtual bool Contains(string serviceName, Type serviceType)
// Use the standard IContainer.Contains(Type)
// if the service name is blank
if (serviceName == string.Empty)
return Contains(serviceType);

return _namedFactories.ContainsKey(serviceName) &&

public virtual object GetService(string serviceName, Type serviceType)
// Used the other GetService method if
// the name is blank
if (serviceName == string.Empty)
return GetService(serviceType);

// Determine if the service exists, and
// suppress the errors if necessary
bool exists = Contains(serviceName, serviceType);
if (!exists && SuppressErrors)
return null;

if (!exists && SuppressErrors != true)
throw new NamedServiceNotFoundException(serviceName, serviceType);

var factory = _namedFactories[serviceName][serviceType];

// Make sure that the factory exists
if (factory == null)
return null;

return factory.CreateInstance(this);

As you can see, there's nothing special about this code. Some might even scoff at it since it's too minimalistic to be useful. After all, one might say that an IoC container has far more responsibilities than just object instantiation. Ninject, for example has features such as contextual binding and method interception. Surely this isn't all there is to LinFu.IoC's features, is it?

Bend it like Ockham

Despite the varying complexity of most (if not all) IoC containers in the field, logically speaking, the code listed above is the absolute minimum amount of code necessary to separate the instantiation of a service instance from its actual client code. When you request a service instance from a given IoC container (whether it be LinFu, Ninject or countless other containers out there), there has to be some point where the container has to decide if that service instance can be created, as well as manage the lifetime of that service once it is already out of the container. As most of us IoC container developers know, there's quite a lot more to a container than just managing the lifetime of its individual services. Creating the instance is only the first step, and I'll show you how LinFu version 2's new IoC container will implement the some of the same features without sacrificing its relatively-horizontal learning curve.

The Pattern of Other Containers

Typically, these containers will use either property setter injection or constructor injection to autowire together all of the dependencies that an application might need during its lifetime. In addition, they might implement additional features such as interception, logging, and AOP. However, despite the differences in features among containers, there are two points where these features are commonly applied:
  • When a service is about to be created (e.g. constructor injection) or,
  • When a service is already instantiated (e.g. property setter injection, or interception)
This implies that a developer can add additional features to their respective IoC container simply by controlling the point where the service is going to be created as well as controlling the point where the service has been recently instantiated. In fact, if you can isolate those two points from the rest of the container, you can effectively add new features without affecting the rest of the code.

Now the reason why LinFu's IoC container can get away with such simple code is because it actually delegates its factory methods to an instance of the IFactory interface:

   public interface IFactory
object CreateInstance(IContainer container);

LinFu's IoC container uses each factory instance to determine how a service implementation should be instantiated, and each factory instance, in turn, is responsible for managing the lifetime of each component that it creates. With that in mind, the only thing that you have to do to extend LinFu's IoC container is to control how each factory creates its object instances (such as deciding which constructor and constructor arguments to use when implementing constructor injection) and control the instances that come out of each factory.

For example, if I wanted to add interception to LinFu.IoC, all I have to do is wrap a Decorator around an IContainer (or INamedContainer) instance that wraps each service instance in a proxy:

public class ContainerDecorator : IContainer
private IContainer _container;
public ContainerDecorator(IContainer realContainer)
_container = realContainer;
// Other methods skipped for brevity
public object GetService(Type serviceType);
// Grab the service instance
var result = container.GetService(serviceType);

// Wrap the instance, if possible
if (result != null)
return SomeProxyFactory.Wrap(result);

// Otherwise return the original instance
return result;

...and in the client code, using the additional decorator is as easy as:

var container = new ContainerDecorator(new SimpleContainer());

// Use the container somehow and transparently use the decorator to wrap the
// result
var service = container.GetService<ISomeServiceType>();

// ...

As you can see, the implementation of LinFu.IoC is very straightforward, and there's really nothing exotic about the design. For those of you who were probably wondering why LinFu.IoC isn't using generics, here's the list of extension methods that completes the design:

public static class ContainerExtensions
public static T GetService(this IContainer container)
where T : class
var serviceType = typeof (T);
return container.GetService(serviceType) as T;
public static T GetService(this INamedContainer container, string serviceName)
where T : class
return container.GetService(serviceName, typeof (T)) as T;
public static void AddFactory(this INamedContainer container, string serviceName, IFactory factory)
IFactory adapter = new FactoryAdapter(factory);
container.AddFactory(serviceName, typeof (T), adapter);

public static void AddFactory(this IContainer container, IFactory factory)
IFactory adapter = new FactoryAdapter(factory);
container.AddFactory(typeof(T), adapter);
public static void AddService(this IContainer container, T instance)
container.AddFactory(typeof (T), new InstanceFactory(instance));

Again, there's nothing unconventional in the design. In the end, it's the simplicity that matters most, and that is the difference that LinFu.IoC offers.

Wednesday, July 30, 2008

The LinFu Reimplementation Plan, and Dogfooding

Before I hit the ground coding, let's go over some of the features that were in LinFu v1.0 that will also be in 2.0:
  1. Dynamic Proxies
  2. Late Binding / Multiple Dispatch
  3. Duck Typing
  4. Mixins
  5. Universal Event Handling
  6. Closures with Lambda Arguments
  7. Design By Contract
  8. AOP (static and dynamic weaving)
  9. Inversion of Control / Dependency Injection
  10. Adaptive Object Models
  11. A MyXaml Engine Clone
Aside from the fact that v1.0 has a fairly hefty feature list, one thing that I've noticed with the source is that despite those features, LinFu itself doesn't really use its own IoC or DbC facilities to improve the quality of its own code, and that's a wasted opportunity.

With that in mind, I've decided to implement the following features first:
  • Inversion of Control / Dependency Injection
  • Dynamic Proxies
  • Design by Contract
  • Static AOP Weaving
Building an IoC/DI container will help enforce a separation of concerns, and using Design by Contract in tandem with TDD will eliminate over 90% of the bugs in the code. The reason why I'm also implementing the static AOP weaving and dynamic proxy generator first is that there has to be a way to transparently inject those contracts into a service instance using a dynamic proxy without having to clutter the original source code. In addition, using the static AOP weaving in a debug build will allow me to dynamically inject diagnostic code without affecting the actual release build.

As for LinFu's Design by Contract v3.0, my goal is to make it injection-agnostic. That means that the library itself should be completely unaware of how it's actually being injected into a service instance. It will allow you to inject contracts using a 3rd-party dynamic proxy generator (such as Castle), and most importantly, it should make no distinction between LinFu's static AOP injection and its own proxy generator.

Probably the most striking difference that you'll see between v1 and v2 is that LinFu will no longer be split into multiple projects (aside from PostWeaver.exe, and the MSBuild task for LinFu.AOP). There might be some who might say that clumping all of LinFu into one DLL violates the principle of Separation of Concerns, but in practice, it will save you an untold amount of headaches when managing your project dependencies.

I realize that rebuilding LinFu is a very tall order, and I'm putting my heart and soul into this one to make sure that it's the best code that I'll ever write. This is going to take some time to redo, and I'll keep posting more and more updates on my blog as time progresses.

Tuesday, July 29, 2008

Behavior-Driven Development to the Rescue?

I've been trying to wrap my head around how I can increase LinFu's test coverage rate for over a week now, and I have to admit that doing DDT testing (aka TDD in reverse, or post-hoc unit testing) is much more difficult than its TDD counterpart.

In contrast, TDD seems to apply a bottom-up approach to ensure that each component is functioning, and in LinFu's case, I'm going to need a top-down testing approach to ensure that all of LinFu's features work as advertised. My intent is to write each test as a specification for LinFu's behavior, and each one of these tests will ensure that LinFu behaves according to its specification.

It's by no means perfect, but it's the only practical solution that I can apply to the existing code base without having to rewrite it. At best, it seems like an ugly hack since I'll be effectively doing black box testing against LinFu instead of getting the 100% test coverage.

The other alternative, of course, is that I can do a complete rewrite of LinFu (presumably version 2.0) from scratch. (It's not a pretty option, but then again, it's no better than having to do post-hoc unit testing).

So here is my question for the developer community at large: Which option should I take, and why? If I do LinFu v2.0 with a 100% test coverage rate, will that up the adoption rate, or will LinFu v1.0 with specification tests added be sufficient enough to fix the test coverage problems?

Wednesday, July 23, 2008

LinFu, and Biting the Testing Bullet.

Ok, I just have to admit it. LinFu still needs a lot more work. The test coverage is still 'awefully low', and despite the fact that I've kept my code clean and simple, it still doesn't take away from the fact that other programmers rely on automated unit tests to verify that your code works as advertised. I think Jeremy Miller said it best when he sent me this email:

I'm giving you an A+ for the outright coolness of LinFu and the Comp Sci nature of things, but I'm questioning the software engineering. To put it another way, I think you'll get far more adoption of LinFu if you have a better story to tell about the testing. If you retrofit a battery of automated tests to at least cover the dynamic proxy and maybe the AOP, I'd be very interested in using LinFu inside my own StructureMap project.

Jeremy definitely has a point there, and in some ways, it's a bitter pill for me to swallow. The bottom line is that LinFu won't get widespread adoption unless I can increase its the test coverage rate. The irony here is that since I have a low test coverage rate from the start, I'll be subjecting myself to some of the same ills that I woefully complained about in other developers.

With that in mind, I've decided to suspend all new development work on LinFu until I can resolve the test coverage issue. I will find a way to get to 100% unit test coverage, even if it means that I'll have to rewrite everything from scratch.

LinFu is officially on lockdown mode, and I've got some major cleaning up to do.

Sunday, June 8, 2008

The Forced Hiatus and the Faulty Laptop.

Today I'll be sending my laptop back to the manufacturer for repairs, and that means all my development work (including LinFu) will be effectively suspended until I can get this issue resolved. According to the manufacturer, the turnaround time should take about 7-10 business days (roughly two calendar weeks).

Meanwhile, the only 'hardware' that I'll have at my disposal will be Pen and Paper (tm), and I still have more than a few things lined up on the LinFu drawing board, even without a compiler. Development is going to screech to a halt in the next few weeks, and then I'll be back with some pretty hefty updates to LinFu. Stay tuned :)

Tuesday, April 1, 2008

Optimistic vs. Pessimistic Design: Which one do you practice?

Lately, I've been noticing a trend in some of the object-relational mapping (ORM) tools in the market place, and the pattern that's emerging is interesting, to say the least.

In general, their feature sets seem to fall into one of these categories:

Pessimistic Design - The designers don't know which features their users will actually use, so they decide to implement nearly *every* possible mapping feature and then leave the end-user to decide how to use their ORM. This approach gives the broadest amount of features but sacrifices simplicity for documentation.

Optimistic Design - The designers assume that you're only going to use 20% of its functionality and implement 80% of the features that would be used in 100% of the mapping cases. They provide you with a general framework for the mapping and the change tracking, and they leave it to you (as the end user) to customize it to your needs. This approach makes the ORM easy to use, but the tradeoff is that it only implements a minimal feature set. The upside to this is that the code is so easy to use that it requires little to no documentation at all. It's practically self-documenting code.

From what I've seen so far, a lot of ORM implement pessimistic design, but very few actually implement the optimistic approach. Do the pessimistic designers assume that their end-users are incapable of implementing their own features, or is an optimistic approach too minimalistic to be useful at all?

With this in mind, it's quite tempting for me to write an ORM that uses an optimistic design approach. There might be some value in having an ORM that lets you do your job in a few minutes without having to sift through dozens of pages of tutorials. I'm a big pundit for large feature sets, but in the end, there's no substitute for pure simplicity.

Thursday, March 20, 2008

LinFu.DynamicModel, MxClone, and the Art of Adaptive Object Models

I've done it! :) Both the LinFu.DynamicModel and the MxClone (the MyXaml Engine Clone) libraries are ready for production use, and I can't wait to get started on writing the CP articles for both libraries.

A Tale of Two Approaches

As I mentioned in previous posts, LinFu.DynamicModel allows you to dynamically create an entire object model in memory at runtime without having to recompile your application. With LinFu.DynamicModel, you can either construct the model directly through code, or you can use the MxClone to create the model for you, using XML markup. I'll briefly go over each approach in the following sections, but before I do that, let's take a look at the interface implementation that we're going to dynamically generate:

A Canonical Approach: The Person Interface

Let's suppose that I wanted to dynamically create a dynamic type that looks like the following interface:

public interface IPerson
int Age { get; set; }
string Name { get; set; }

Using LinFu.DynamicModel in Your Code

Here's how you can dynamically create a type that implements the IPerson interface:

// TypeSpec objects are type descriptions that can be modified at runtime
TypeSpec personSpec = new TypeSpec()

// Notice the strongly-typed properties
Properties =
new Property<int>("Age"),
new Property<string>("Name")

// This will return true
bool isPerson = personSpec.LooksLike<IPerson>();
var person = personSpec.CreateDuck<IPerson>();

// Use the person object just like any other POCO
person.Age = 18;
person.Name = "Me";
// ...

Thanks to C#'s 3.0 new language features, you can easily create a model in memory with LinFu in relatively few lines of code. What makes this particularly interesting, however, is the fact that as the given TypeSpec changes, all of the IPerson instances that rely on that TypeSpec automatically "change" their behavior to match the newly-modified Person TypeSpec.

Using LinFu.DynamicModel with MxClone

Needless to say, there's a myriad of things you can do with this sort of technology, but it gets better--you can describe the same model through XML, using a MyXaml-style syntax:

<?xml version="1.0" encoding="utf-8"?>
<Root xmlns="LinFu.Reflection.Extensions, Version=, Culture=neutral, PublicKeyToken=null"
xmlns:def="Definition" xmlns:set="Setters">
<TypeSpec def:Name="PersonType" Name="PersonType">
<PropertySpec PropertyName="Name"
<PropertySpec PropertyName="Age"



As you can see, the XML syntax for MxClone is similar to MyXaml, with the exception of the set:Behavior element. MxClone allows you to assign object references to properties without having to give it a specific reference name (e.g., {SomeName}), and in this case, the set:Behavior element means that I'm assigning an object reference of type 'PropertyBag' to a property named "Behavior" on the PropertySpec type. (The PropertyBag class, in turn, is responsible for maintaining the state of each property on every given type instance--but for now, I'll save that for the upcoming LinFu article on CP)

In essence, MxClone is actually constructing the same TypeSpec in memory using XML markup. Having the model specified in XML allows you to change it at runtime without recompiling the application, and that could come in handy if you need to change your business model with minimal downtime. Anyway, back to the markup...

From XML to TypeSpec, in 15 Lines of Code

Now that we have the XML markup, the next thing you might be wondering about is the client code: exactly how do you convert that markup into a running TypeSpec? Here's how you do it:

// Load the engine into the container
string directory = AppDomain.CurrentDomain.BaseDirectory;
SimpleContainer container = new SimpleContainer();
Loader loader = new Loader(container);
loader.LoadDirectory(directory, "*.dll");

IMxEngine engine = container.GetService();

// The instance holder will
// store the object graph once
// it's been instantiated by the engine
IInstanceHolder holder = new DefaultInstanceHolder();
string file = @"C:\YourDirectory\SimpleTypeSpecSample.xml";
engine.Execute(file, holder);

TypeSpec spec = holder.GetInstance("PersonType");
bool isPerson = spec.LooksLike();

// Use the person class normally
IPerson person = spec.CreateDuck();
person.Age = 18;
person.Name = "Me";

In the example above, I used the Simple.IOC container to instantiate the MxClone Engine. The engine, in turn, converted the XML markup into a working Person TypeSpec, and lastly, I used that same TypeSpec instance to create the IPerson instance. It's just that simple. :)


As you can see, there's quite a bit of development going on with LinFu.DynamicModel and LinFu.MxClone, and like everything else in the LinFu project, it will all remain under the LGPL license. I've put my heart and soul into this project, and hopefully, everyone will see that once the next set of LinFu articles comes out on CP. Stay tuned!

Monday, March 17, 2008

Using Selective Method Weaving for LinFu.AOP

A while back, someone asked me if there was a way to make LinFu.AOP weave only certain types of methods and properties, and at the time, LinFu.AOP wasn't capable of doing that--that is, until now.

Here's how you do it. All you need to do is provide your own custom implementation of an interface named IMethodFilter and put that implementation in the same directory as LinFu.Aop.Weavers.Cecil.dll, and you're good to go. Here's a simple example:

[Implements(typeof(IMethodFilter), LifecycleType.OncePerRequest)]
public class MySampleCustomFilter : IMethodFilter
public bool ShouldWeave(MethodDefinition method)
// Intercept only public methods
return method.IsPublic;


All you have to do is put that in a separate DLL and make sure that the assembly is located in the same directory as LinFu.Aop.Weavers.dll, and you can customize it to your heart's content. It's just that simple. Enjoy!

Thursday, March 13, 2008

A Peek at LinFu.DynamicObject

Although it's been quite a while since my last post, LinFu has been coming along quite nicely with some recent additions. In the past month, I've managed to create two new things for LinFu:

  • A Dynamic Typing System for LinFu.DynamicObject, and
  • A MyXaml clone that will deserialize the DynamicModel from disk and load it into memory.

The Current State of Affairs

In LinFu's current state, you can only dynamically add properties and methods to DynamicObjects on a per-instance basis. Currently, there's no way to create a prototype for an entire set of DynamicObject instances and have all of those instances share the same conceptual prototype. For example, suppose that I wanted to create a Person type that looks something like this:

public interface IPerson
string Name { get; set; }
int Age { get; set; }

In order to have a set of dynamic objects emulate a IPerson instance, I would have to manually generate a Name and an Age property on each dynamic object that I needed to use. While such a scenario might be acceptable if I only needed to use a few DynamicObjects, the story starts to become quite different if that small few suddenly becomes a few hundred thousand. Suffice to say, there's quite a cost in having to set up a couple hundred thousand dynamic objects in memory at runtime. There must be a better way to do this, and thus, LinFu.DynamicModel was born.

Build Your Own Model, All at Runtime

LinFu.DynamicModel allows you to create an in-memory type specification (or prototype) of what you want your DynamicObjects to look like. You can add or remove methods and properties to this specification at runtime, all without having to create a single DynamicObject. Any DynamicObject that is attached to that type specification will effectively have all the properties and methods of that spec. The best part about all this is that all changes you make to a spec at runtime will be reflected in every single DynamicObject that uses that type specification.

For example, let's suppose that I wanted to create an implementation of the IPerson interface and have two DynamicObjects share the same conceptual Person type. Here's how it would look like:

DynamicObject firstPerson = new DynamicObject();
DynamicObject secondPerson = new DynamicObject();

// Both of these LooksLike() calls will return false
// since IPerson has yet to be implemented
Console.WriteLine("Object #1: IsPerson? {0}", firstPerson.LooksLike());
Console.WriteLine("Object #2: IsPerson? {0}", secondPerson.LooksLike());

// Create a person type with only the Name property implemented
TypeSpec personSpec = new TypeSpec();
personSpec.AddProperty("Name", typeof(string));

DynamicType personType = new DynamicType(personSpec);

// Make both DynamicObjects act like the person type
firstPerson += personType;
secondPerson += personType;

// Note: This still will return false since we haven't implemented the Age property
Console.WriteLine("Object #1: IsPerson? {0}", firstPerson.LooksLike());
Console.WriteLine("Object #2: IsPerson? {0}", secondPerson.LooksLike());

// Finally, implement the age property so that both types look like an IPerson
personSpec.AddProperty("Age", typeof(int));

// Note: Both DynamicObject instance calls to LooksLike() will now return true
// since the type they refer to now implements IPerson
Console.WriteLine("Object #1: IsPerson? {0}", firstPerson.LooksLike());
Console.WriteLine("Object #2: IsPerson? {0}", secondPerson.LooksLike());

// Use both instances normally as IPerson instances...
IPerson first = firstPerson.CreateDuck();
IPerson second = secondPerson.CreateDuck();

// ...

As you probably noticed from the example above, the only thing I needed to do was modify the TypeSpec instance and both DynamicObjects automatically changed their behavior to match the given TypeSpec. In theory, this will allow you to effectively generate an entire object model in memory without having to recompile the application. In fact, the only thing you would need at this point is a reliable way to deserialize the object model from disk. At first, using the .NET BCL's serialization mechanisms might be the easiest way to do this, but LinFu.DynamicModel's metamodel heavily relies on interfaces to provide each method and property implementation, and those interfaces cannot be serialized to disk by the classes in the System.Runtime.Serialization namespace.

Legally Infeasible

Now, since MyXaml is very good at instantiating object graphs, and LinFu's DynamicModel is nothing but a metamodel object graph, the next logical step would be to use MyXaml, but there's just one problem--MyXaml is licensed under the GPL, not the LGPL, which means that MyXaml can't be used in commercial applications unless you obtain a commercial license from Marc Clifton, or you publish the source code to your own commercial applications. Since I'm committed to making all of LinFu available under the LGPL, I had no choice but to write my own MyXaml engine from scratch, and hopefully, I can cover that in my next blog post. For now, all I can say about my unnamed MyXaml clone is that it's some of the best code that I've ever written, and this one is definitely worth the wait.

In the meantime, this should whet our appetite for what's to come in LinFu, and the future looks bright indeed.

Stay tuned!

Thursday, February 7, 2008

LinFu.DynamicObject and Dynamic Object Models

I've been playing around with LinFu.DynamicObject and I've discovered a way to implement a dynamic typing system that can be changed at runtime. That means that with LinFu.DynamicObject, you can assign it to a particular DynamicType instance and any DynamicObjects that depend on that same instance will actually change their methods and properties at runtime to match that particular DynamicType!

Adaptive Object Models, anyone? :)

Dynamic Method Dispatch is one thing that LinFu can do very well, and pretty soon, you'll be able to reconfigure an entire object model in memory without having to recompile the application.

Suffice to say, things are going to get interesting with LinFu as the series of articles progresses.

Stay tuned!

Friday, February 1, 2008

The Model, View, and (Virtual) Presenter Pattern

One of the greatest weaknesses of the
MVP/MVC pattern is that although the the model is completely separated from the view (and vice-versa), the view in the MVP pattern has to have a concrete dependency on its corresponding Presenter in order to function. At first, there doesn't seem to be a way to completely isolate all three components of the MVP pattern from each other, given that the view has to have a reference to a concrete presenter. The presenter, on the other hand, knows nothing about the concrete view, other than the IView interface that is implemented by the view itself; it's a one way dependency, and yet, something just doesn't 'feel' right here...

The Epiphany

...and then that's when the questions started to hit me:
Does the presenter even have to be a concrete presenter at all? Is it possible to replace a concrete presenter with an interface type, and what would that interface look like? Are all presenters the same, or do they just all represent some sort of abstract concept that can't be centralized into a single common class?

My proposal for changing the MVP pattern is this: What if we convert the concept of the presenter from a concrete class to an abstract metaclass? If we change the presenter from a concrete class to an abstract implementation of a concept, we can effectively eliminate the dependency between all three parts of the MVP triad. It might sound complex, but the implementation is actually quite simple. In this variant of the MVP pattern, we can completely eliminate the view's dependency on a concrete presenter by converting the concrete presenter dependency into a collection of interfaces that the view requires in order to function.

A Quixotic Attempt

A naive approach would be to try to find a common interface to be implemented by presenters, but this poses a problem--no two presenters will ever be exactly alike. A presenter that will handle a list view won't always have the same interface as a presenter that handles a date field. In addition, there might be presenters which might hold some business or validation logic that other presenters might not necessarily share. In other words, we're dealing with a situation where each presenter interface allmust be heterogenous for each view type, and that makes it difficult to group all of the presenters into a single interface that could be used by each view type.

Dead End?

At first, it might seem like we have no choice but to make each presenter concrete and customize each one of them to fit their corresponding views--but what if we refactored each one of these concrete presenters into multiple interface dependencies for each view? If you think about it, a concrete presenter is nothing but a collection of different responsibilities assigned to a concrete interface. For example, a DatePresenter class might have a few methods that check if the date value presented in the view is valid. The same DatePresenter class also might have methods which can persist the date value to the database. The crux of the concrete presenter in the MVP pattern is that the date view relies on this same DatePresenter to control its behavior. There's a one-way separation between the view and the presenter, and there has to be a way to completely isolate the presenter from the view itself.

An Unnecessary Coupling

A view (for the most part) doesn't need a reference to a concrete presenter class as much as it needs a reference to the interfaces and responsibilities that each one of those interfaces represent. In fact, if I were to refactor a concrete presenter, extract each one of its interfaces, and have each one of those interfaces represent a responsibility that the target view requires, it almost seems like I've converted the concrete presenter into a de facto service container.

Each presenter responsibility corresponds to a service, and each service corresponds to an interface type. Since no two presenters are alike, one could even say that each presenter has a list of services that it offers to each view. So for me, the next logical question is this: If concrete presenters are nothing but de facto service containers, why not use a real service container (aka IoC container) and ditch the concrete dependency altogether?

If a concrete presenter is actually nothing but a degenerate IoC container in disguise, then I can take each one of the view types and replace their concrete presenter dependencies with a single dependency--a dependency on real IoC container by itself. What makes this interesting is that in this variant of the MVP pattern, the 'P' in the MVP pattern no longer exists as a concrete class. The view's concrete dependency on the presenter has been supplanted by interface dependencies supplied by an IoC container. Using this scheme, the view knows nothing about the actual presenter concrete class, and the presenter knows nothing about the concrete view class. As an added bonus, we can even separate the presenter from the concrete model by having the presenter rely on interfaces supplied by the model, and vice versa. The best part about all this is that (aside from the interface dependencies) all three parts of the MVP triad are completely isolated from one another. The only dependency that all three parts of the MV(P) pattern share is the IoC container itself, and since most IoC containers are easily configurable by design (namely LinFu), this dynamically gives us complete control over all the dependencies of a given application...

Note: So far, all of this is just theory, and I have to write it down somewhere before I forget it. I think this pattern can help quite a lot of people, and hopefully I can test it soon.

Tuesday, January 29, 2008

LinFu.AOP Released!

After two long weeks of pounding away at the keyboard, I'm finally finished with the article for LinFu.AOP, and I'm proud to say that it's finally been released to the SVN repository for general use!

So if you haven't downloaded a copy of LinFu.AOP yet, feel free to update your SVN copy to the latest revision as soon as possible--trust me, you don't want to miss this one! :)

Now, if only CP can publish my article fast enough...

Saturday, January 19, 2008

Writer's Block, or Write this Block?

I've been incredibly busy over the past few weeks so I haven't had time to update my blog until now. I've pretty much temporarily frozen any further development with LinFu (aside from bug fixes) until I can get the Part VI article out the door and released to CodeProject. I don't know why, but lately I've caught a really bad case of writer's block. It seems like there's so many topics that I need to cover for Part VI, but I can't seem to flesh out all the details without reading through the current draft and finding glaring omissions in the documentation itself. Call me an obsessive perfectionist, but I won't release any article unless I know that it meets my standards.

I can't really quantify it, but my intuition is telling me something wrong here--and I won't rest until I can finally get this article fixed.

Sunday, January 6, 2008

A Familiar Story, Told by LinFu.AOP

Here's a simple story that shows what one can do with LinFu.AOP. Note the code listing below:

public class Person
public string Name { get; set; }
public int Age { get; set; }
public void Speak()
Console.WriteLine("Hello, World!");

public class Demon
public string Name
get { return "Captain Howdy"; }
set { throw new InvalidOperationException("Are you crazy??"); }
public int Age
get { return 999999; }
set { }
public void Possess(Person person)
DynamicObject dynamic = new DynamicObject(this);
public void Deposses(Person person)
throw new InvalidOperationException("Fat chance, buddy!");
public void MakeHeadSpin()
// ...
public void VomitGreenStuff()
// ...
public void Speak()
Console.WriteLine("This girl is mine!");
class Program
static void Main(string[] args)
// There once was a nice little girl...
Person girl = new Person() { Name = "Linda Blair", Age = 6 };

// Who spoke in a soft voice..

// Until one day, she played with some crazy oija board named 'LinFu.AOP', and
// then everything changed...
Demon demon = new Demon();
IModifiableType modified = girl;
girl.IsInterceptionEnabled = true;

// Then some devoted priest came along and spoke with the girl, and she said:

// He took pity on the girl, and tried to free her from the demon.

// The demon resisted, but the priest was smart, and in the end,
// he subdued the demon.
girl.IsInterceptionEnabled = false;

// ..the end

The Devil in the Details

Now, if you look at that code listing above, you'll notice that the Person class has no idea that it's being intercepted at all. In fact, poor little Linda doesn't know the trouble she's getting into. The Demon class was able to possess Person types because LinFu.AOP modified the Person class to allow itself to be dynamically intercepted at runtime, all without the knowledge of the said victim.

What makes this interesting, however, is that interception can be easily turned on or off depending on the value of the IsInterceptionEnabled property. In fact, if interception is turned off, the Person class will behave just like any other normal person without any performance penalties that are typically incurred by pass-through interception. If interception is turned on, of course, you'll be bound to have some performance overhead incurred, but the added flexibility bonus is staggering. With the slight decrease in performance, you can effectively take over the implementation of the entire class at runtime, and you can even customize it on a per-instance basis.

Think about it. :)

LinFu AOP, Reinvented

After four days of coding and refactoring, I've done it! I've managed to rewrite the original version of LinFu.AOP to address all of the issues that I mentioned in previous posts, and now I only need to write the MSBuild task and the command-line weaver before I can go ahead and start working on the CP article. I know that LinFu.AOP has been vaporware as of late, but I can guarantee you that this is definitely worth the wait.

Aside from the features that I mentioned earlier in this blog, LinFu.AOP will add some interesting features to the LinFu Framework, such as:

Even simpler Simple.IOC integration

With LinFu.AOP, you no longer have to even reference Simple.IOC.dll in your application to use the container. For example, instantiating an IDbConnection type from a SimpleContainer instance will be easy as:

IDbConnection myConnection = New.Instance;

...that's it! Behind the scenes, LinFu.AOP will actually intercept the call made to the following class:

public class New
public static T Instance
get { throw new NotImplementedException(); }

Now, believe it or not, the code listing above is the actual implementation of the New class. What I'm actually doing is using LinFu.AOP to redirect the request for an IDbConnection instance to an appropriate factory method (in this case, the Simple.IOC container). What makes this even more interesting is that it employs the same type of XCOPY-style configuration that you would expect from LinFu; it means that if you wanted to inject any more dependencies into the container, all you have to do is drop the new dependencies into the directories, and the container will rebuild itself and that dependency will be available in the next New.Instance call!

LinFu.DynamicProxy 'Submersion'

One of LinFu.DynamicProxy's weaknesses is that its interceptor instances can only be bound to an unsealed type with all of its public methods marked virtual. With LinFu.AOP, that limitation no longer applies.

LinFu.AOP allows LinFu.DynamicProxy interceptors to intercept methods and properties on type instances without even using the proxy generator itself. This means that when LinFu.AOP intercepts a method call done against a target type, there is no intermediate proxy doing the interception. LinFu.AOP rewrites the IL in your method body and redirects it to your interceptor, all at runtime. You can even reuse the old method implementation as if you were still using DynamicProxy.

One could even say that the inteceptor has 'submerged' itself into the type implementation because the interceptor can still intercept any method on any given type as if it were still attached to the proxy--however, what makes it 'submerged' is the fact that you're actually using the true object instance itself!

To take this concept even further, LinFu.AOP supports two levels of method interception: Class-Based, and Instance-Based.

This means that you can either intercept a particular method across all instances of a given type, OR you can actually customize the method replacement (or interceptor) based on the current instance that you're using. Think about that for a moment...

...and while you're thinking about that, I'm going to go back and polish this thing up. :)

Thursday, January 3, 2008

On Donuts and Method Interception Styles

To keep the ball rolling, LinFu.AOP2 will support the following styles of method interception:

Donut Interception - This means that when a method is intercepted, its original implementation (a.k.a. its method body) will be left intact, but LinFu.AOP2 will inject additional behavior around the original method body--hence, the donut moniker. This can be useful if you want to inspect the input and the output of a given method without altering its implementation.

Donut Hole Interception - This means that when a method is intercepted, its original implementation is completely discarded and replaced with a different implementation altogether.

To make this interesting, LinFu.AOP allows both styles of interception to overlap each other, all at runtime. That means you can inject code 'around' a method body, and you can even replace that method body with something else altogether. Needless to say, this new framework offers a staggering amount of power not readily available in any .NET language today, and the possibilities with it are truly limitless.

(Meanwhile, all this talk of donuts is making me hungry, so I'm off to breakfast...)

LinFu.AOP2 Specifications and Requirements

In general, LinFu.AOP2 must meet the following requirements:

Pervasive Method Interception - It must intercept both instance and static methods on all types, regardless of whether or not the target types are sealed or unsealed. This also includes non-virtual methods.

Type Initialization - It must intercept constructor calls and allow its users to perform custom initialization steps to each type that is created in memory.

No Proxy Required - It must do all of the above interception operations without using any form of DynamicProxy generator (whether it is LinFu, Castle, or whatnot).

Completely Transparent - The target library should not even be aware of any changes made to it by the AOP library. When I look at the source for the target library, there should be no trace or reference to any of the changes made by the new AOP library. In short, all changes should be completely invisible.

No Attributes Required - This means that it should not force the end-user to use .NET attributes at all to specify where any code should be inserted or injected. I might sound like a purist, but in my opinion, the very act of scattering attributes across your application is crosscutting in itself--and that's exactly what AOP is trying to avoid, and I'll do my best to avoid that as well.

Runtime Injection and Interception - LinFu.AOP2 must allow the end user developer to arbitrarily inject or insert any piece of code into an application, all at runtime, not compile time. This is a huge contrast to PostSharp, which only allows you to inject new method behavior at post-build (compile) time.

Language-Independent - It must be able to be used from nearly any .NET language, regardless of the target language's syntax.

Strong Name Signature Stripping - It *should* be able to strip the strong name signature right off of any signed assembly. Given the controversial nature of this particular topic, this feature is completely optional.

Fortunately, since LinFu.AOP1 met seven out of eight of these requirements (that is, everything but the strong name signature stripping), most of the implementation research has already been completed. The only thing left to do is to refine the implementation, and hopefully, it will be ready for an article release on CodeProject.

I'll post as much design notes as I can on this blog to keep everyone posted. Once I come up with any breakthroughs, I'll post some code on this blog for everyone to peruse.

Wednesday, January 2, 2008

Back to the Drawing Board

Although my working prototype of LinFu.AOP has some stunning features such as pervasive
method interception and transparent code injection, at this point, it doesn't quite yet meet my quality standards for something that I would release to the general public, so I'm going to scrap it and start off from scratch.

Queue LinFu.AOP, take two...

Ratings by outbrain