Oren Eini

CEO of RavenDB

a NoSQL Open Source Document Database

Get in touch with me:

oren@ravendb.net +972 52-548-6969

Posts: 7,640
|
Comments: 51,260
Privacy Policy · Terms
filter by tags archive
time to read 4 min | 613 words

In my previous post I introduced the basis of context as an architectural pattern. Now I want to talk about how we can implement that using Windsor and a new extensibility point: IModelInterceptersSelector.

The interface is defined as:

/// <summary>
/// Select the appropriate interecptors based on the application specific
/// business logic
/// </summary>
public interface IModelInterceptorsSelector
{
    /// <summary>
    /// Select the appropriate intereceptor references.
    /// The intereceptor references aren't neccessarily registered in the model.Intereceptors
    /// </summary>
    /// <param name="model">The model to select the interceptors for</param>
    /// <returns>The intereceptors for this model (in the current context) or a null reference</returns>
    /// <remarks>
    /// If the selector is not interested in modifying the interceptors for this model, it 
    /// should return a null reference and the next selector in line would be executed (or the default
    /// model.Interceptors).
    /// If the selector return a non null value, this is the value that is used, and the model.Interectors are ignored, if this
    /// is not the desirable behavior, you need to merge your interceptors with the ones in model.Interecptors yourself.
    /// </remarks>
    InterceptorReference[] SelectInterceptors(ComponentModel model);

    /// <summary>
    /// Determain whatever the specified has interecptors.
    /// The selector should only return true from this method if it has determained that is
    /// a model that it would likely add interceptors to.
    /// </summary>
    /// <param name="model">The model</param>
    /// <returns>Whatever this selector is likely to add intereceptors to the specified model</returns>
    bool HasInterceptors(ComponentModel model);
}

And registering it in the container is simply:

container.Kernel.ProxyFactory.AddInterceptorSelector(selector);

Interceptors are the basis of AOP, but traditionally, you didn't get a lot of choices in how you compose your interceptors at runtime. Using IModelInterceptersSelector make it extremely easy to modify the selection of interceptors based on relevant business logic.

Let us take the following example. We have a warehouse service that we want to add caching to. However, we can't use the cache in the request comes from the fulfillment service. First, we define the caching interceptor, then, we define the logic that controls adding or removing it.

public class WarehouseCachingInterceptorSelector : IModelInterceptorsSelector
{
    public InterceptorReference[] SelectInterceptors(ComponentModel model)
    {
        if(model.Service!=typeof(IWarehouse))
            return null;
        if(Origin.IsFromFulfillment)
            return null;
        return new InterceptorReference[]{new InterceptorReference(typeof(WarehouseCachingInterceptor)), };
    }

    public bool HasInterceptors(ComponentModel model)
    {
        return model.Service == typeof (IWarehouse);
    }
}

And now we get caching for everything except for fulfillment. And we get this in a clean and very easy to understand way. :-D

time to read 3 min | 527 words

In my previous post I introduced the basis of context as an architectural pattern. Now I want to talk about how we can implement that using Windsor and a new extensibility point: IHandlerSelector.

The interface is defined as:

/// <summary>
/// Implementors of this interface allow to extend the way the container perform
/// component resolution based on some application specific business logic.
/// </summary>
/// <remarks>
/// This is the sibling interface to <seealso cref="ISubDependencyResolver"/>.
/// This is dealing strictly with root components, while the <seealso cref="ISubDependencyResolver"/> is dealing with
/// dependent components.
/// </remarks>
public interface IHandlerSelector
{
    /// <summary>
    /// Whatever the selector has an opinion about resolving a component with the 
    /// specified service and key.
    /// </summary>
    /// <param name="key">The service key - can be null</param>
    /// <param name="service">The service interface that we want to resolve</param>
    bool HasOpinionAbout(string key, Type service);

    /// <summary>
    /// Select the appropriate handler from the list of defined handlers.
    /// The returned handler should be a member from the <paramref name="handlers"/> array.
    /// </summary>
    /// <param name="key">The service key - can be null</param>
    /// <param name="service">The service interface that we want to resolve</param>
    /// <param name="handlers">The defined handlers</param>
    /// <returns>The selected handler, or null</returns>
    IHandler SelectHandler(string key, Type service, IHandler[] handlers);
}

And registering it in the container is simply:

container.Kernel.AddHandlerSelector(selector);

A handler selector is asked if it wants to express an opinion on a particular component resolution, based on key (optional) and type. Assuming we say yes, we are called to select the appropriate handler from all the registered handlers that can satisfy that request.

Let us say that we want to recover from the database being down by serving an implementation that reads from only the cache, we can implement it thusly:

public class DataAccessHandlerSelector : IHandlerSelector
{
	bool databaseIsDown = false;

	public DataAccessHandlerSelector()
	{
		DatabaseMonitor.OnChangedState += 
			state => databaseIsDown = state == DatabaseState.Down;
	}

	public bool HasOpinionAbout(string key, Type service)
	{
		return databaseIsDown && service == typeof(IRepository);
	}

	public IHandler SelectHandler(string key, Type service, IHandler[] handlers)
	{
		return handlers.Where(x=>x.ComponentModel.Implementation == typeof(CacheOnlyRepository)).First();
   	}

}

Now we automatically replace, based on our own logic and the current context what type of component the container should resolve.

I am giving the example of detecting infrastructure change, but as important, and as interesting, is the ability to easily use this in order to select services in a multi tenant environment. We can use this approach to perform service overrides all over the place in a way that is natural, easy and extremely powerful.

Have fun...

time to read 5 min | 805 words

I am a big believer in using context in order to drive a system. What do I mean by that?

Note, I am going to talk about the problem in general, and its solution implementation using Windsor. The example is fictitious and is here to represent the problem in a way that allow me to talk about it in isolation, it doesn't necessarily represent good design.

It seems like just about all the applications that I had to deal with recently had to have the notion of system variability. Now, let us make it clear. System variability is a fancy name for the if statement. The problem with the if statement is that when you have a lot of them, it gets pretty tricky to understand what is going on with the system. That is why a common refactoring is replace conditional with polymorphism.

What I am usually talking about is "when we are in this condition, we should do X, otherwise, we should do Y". Let us take the simple idea of a warehouse service. If we are making a call from the web site, it is okay to return data that may not be accurate to the second. If we are calling from the fulfillment service, we need accurate, up to date results. A simple way of handling this is:

public bool ItemIsPhysicallyOnTheShelve(Guid id)
{
	if(Origin == Originators.Website)//can use caching
	{
		var result = Cache.Get<bool?>("item-on-shelve-" + id)
		if(result.HasValue)
			return result.Value;
	}
	// actual work and putting in cache
}

A more interesting example might be different business rules for making order authorization, based on whatever we have a strategic customer or not. In both cases, we have some context for the operation that modify the way that we deal with this operation.

public bool IsValid(Order order, ValidationSummary summary)
{
	IRule[] rules = CurrentCustomer.IsStrategic ?
		strategicCutomerRules : normalCustomerRules;
	foreach(IRule rule in rules)
	{
		rule.Validate(order, summary);
	}
	return summary.HasErrors;
}

One way of dealing with that is as you see in the code samples, get the state from somewhere and make decisions based on that. Another, more advance option is to create:

  • IWarehouseService
  • DefaultWarehouseService
  • CachingWarehouseServiceDecorator

And because decorators are really annoying, we will use AOP to deal with it by creating a caching interceptor.

Now the issue is mere configuration, I can deal with that by flipping bits in the container configuration. The second example can be solved by creating two components with different rule sets and using that. The problem is that this remove the coding issues, but it creates a more subtle and much harder to deal with problems.

If I rely on the container configuration alone, I suddenly have logic there. Important business logic. That is not a good idea, I think. Especially since this means that at some point my code has to make an explicit decision about what component to use, and that breaks the infrastructure independence rule.

What this boil down to is that now I have to manage a lot of the complexity in the application using the container configuration and tie the working of the system into it. That works if the number of variables that I have to juggle is small, but if I have a lot of axes (plural: axis)  that are orthogonal to one another, it is getting complex very fast.

My solution for that problem is to define a service and its context as a cohesive unit. That is, the concept of a service contains its interface, all of its implementations and the business logic required to select which implementation (and configuration) to choose for a given context.

In the warehouse example above, what we will have is:

  • IWarehouseService
  • DefainltWarehouseService
  • WarehouseCachingInterceptor
  • WarehouseInterceptorsSelector

Now all of those are part of the same service. The last one is where we isolate the actual decision about what type of implementation we should get. In this case, we use Windsor's IModelInterecptorsSelector to add additional, context bound, interceptors to the service.

But that is just from the interceptors side, what about the selection of the appropriate rules? We can handle that using ISubDependencyResolver, where we can decide how we want to filter the rules that goes into IWarehouseService based on the context. For that matter, we might have a completely different warehouse implementations, VirtualWarehouseService and PhysicalWarehouseService. And we need to select between them based on some business criteria. We handle that using IHanlderSelector, that make the decision which component to create.

Again, IHandlerSelector, IModelInterceptorsSelector and ISubDependencyResolvers are all implementations of Windsor extensibility mechanisms (my next two posts will cover them in details) that allows us to make it aware of the context that we have in the application.

The purpose of the explicit notion of context is to allow us to deal with the variability in the application in an explicit manner. And that, in turn means that we get much better separation of concerns.

Reading MEF code

time to read 2 min | 400 words

Okay, here is the deal. There is a feature in MEF that I find interesting, the ability to dynamically recompose the imports that an instance have. Well, that is not accurate. that doesn't really interest me. What does interest me is some of the implementation details. Let me explain a bit better.

As I understand the feature, MEF can load the imports from an assembly, and if I drop another file into the appropriate location, it will be able to update my imports collection. Now, what I am interested in is to know whatever MEF allow me to update file itself and update it on the fly. The reason that I am interested in that is to know how this is done without locking the file (loading an assembly usually locks the file, unless you use shadow copy assemblies, which means that you have to use a separate AppDomain).

As you can imagine, this is a very specific need, and I want to go in, figure out if this is possible, and go away.

I started by checking out the MEF code:

svn co https://mef.svn.codeplex.com/svn mef

I just love the SVN integration that CodePlex has.

Now, the only way that MEF can implement this feature is by watching the file system, and that can be done using a FileSystemWatcher. Looking for that, I can see that it appears that DirectoryPartCatalog is using it, which isn't really surprising.

But, going there and reading the code gives us this:

image

Note what isn't there. there is no registration to Changed. This is likely not something that MEF supports.

Okay, one more try. Let us see how it actually load an assembly. We start from Export<T> and GetExportedObject() which calls to GetExportedObjectCore() which shell out to a delegate. Along the way I looked at CompositionException, just to make sure that it doesn't have the same problem as TypeLoadException and the hidden information, it doesn't.

I tried to follow the reference chain, but I quickly got lost, I then tried to figure out how MEF does delayed assembly loading, to see if it is doing anything special there, but I am currently hung at ComposablePartDefinition.Create, which seems promising, but it is accepting a delegate and no one is calling this.

So this looks like it for now.

time to read 3 min | 492 words

Today I decided that I had enough time to get bugs for the 3.5 RC, so I fixed all the remaining bugs, updated the Rhino Mocks 3.5 Documentation, and put the binaries out the site.

For this release, I actually have 4 binary packages. One for .NET 3.5 and one for .NET 2.0, but I have an additional criteria, with the castle assemblies merged (default) and with the castle assemblies included). The reason for having those two options is that people who want to extend Rhino Mocks directly can do it more easily. In general, I suggest using the merged version.

So, what do we actually have here (feature differences from 3.4)?

Features:

  • Assert Act Arrange syntax for mocking
    • Including support for .NET 2.0
  • Added a way to access the mocked method at runtime, using WhenCalled (similar to Do(), but without the pain of having to specify a special delegate).
  • CreateMock() is deprecated and marked with the [Obsolete] attribute. Use StrictMock() instead.
  • Support for mocking interface in C++ that mix native and managed types. (Note, may require that you install kb957541 to get around bug introduced to the framework on SP1).
  • New event raising syntax:
    eventHolder.Raise(stub => stub.Blah += null, this, EventArgs.Empty);
  • Better support for multi threaded replays.
    • Note that access to the mock object is now serialized.
  • Support AssertWasCalled on parial mocks.

Patches:

  • From Sebastian Jancke, adding support for SetPropertyAndIgnoreArguments() and SetPropertyWithArguments( o );
  • From Yann Trevin, adding support for List.Element("MyKey", ...), so we are not limited to just integers.
  • From David Tchepak, adding support for ctor arguments when creating a mock using static method.
  • From Stefan Steinegger - much better support for creating inline constraints.

Improvements:

  • Better handling of exception in raising events from mock objects
  • Better error message when trying to set expectation on properties of a stub.
  • Better error handling for AAA syntax abuse
  • Will give better errors if you call Verify on a mock that is in record mode.
  • Allowing to return to record mode without losing expectations.
  • BackToRecord extension method.
  • AAA syntax now works with Ordering
  • Better error message if trying to use SetupResult on stubbed mock properties.
  • Better error message when trying to mock null instance.

Bug fixes:

  • Fixing an issue with mock objects that expose methods with output parameter of type System.IntPtr.
  • Fixed an issue with merging, would cause issues if you are also using Castle Dynamic Proxy.
  • Fixed various typos
  • Fixed issue with mocking internal classes and interfaces.
  • OutRef params was not copied when creating new expectation from an existing one.
  • Fixing an issue with leaking expectationReplaced in mocks.

FUTURE POSTS

No future posts left, oh my!

RECENT SERIES

  1. API Design (10):
    29 Jan 2026 - Don't try to guess
  2. Recording (20):
    05 Dec 2025 - Build AI that understands your business
  3. Webinar (8):
    16 Sep 2025 - Building AI Agents in RavenDB
  4. RavenDB 7.1 (7):
    11 Jul 2025 - The Gen AI release
  5. Production postmorterm (2):
    11 Jun 2025 - The rookie server's untimely promotion
View all series

Syndication

Main feed ... ...
Comments feed   ... ...