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,597
|
Comments: 51,224
Privacy Policy · Terms
filter by tags archive

Semi Statics

time to read 6 min | 1111 words

I talked about Static pros and cons before. I also promised that I would post my solution to that. To sumrise for those who don't want to read the previous posts:

  • Statics make it easy to access functionality from anywhere in the application.
  • They allow cross cutting concerns to be handled easily by infrastructure code.
  • It is hard to make them safe for multi threading.
  • It is usually hard to test code that uses singletons.

My solution for that is to use a piece from Rhino Commons, the Local.Data hash table. This allow me to put objects that are assured to be local to my current execution, regardless of whatever I am running in a windows or web scenario.

Once I have that, I can create this class:

As you can see, this is a static class* with. The implementation is trivial:

public static class Context

{

       const string DbConnectionKey = "Db.Connection.Key";

 

       public static IDbConnection DbConnection

       {

              get

              {

                     IDbConnection connection = Local.Data[DbConnectionKey] as IDbConnection;

                     if (connection == null)

                           throw new InvalidOperationException("Context was not initialized properly");

                     return connection;

              }

       }

 

       public static IDisposable Initialize(IDbConnection connection)

       {

              LocalData.Data[DbConnectionKey] = connection;

              return new DisposableAction(delegate { Dispose()); }) ;

       }
  . . .

}

The usage is also simple, let us say that I want to do some operation that require the database.  I have some infrastructure code that handles the basic interactions. On the web, I usually use an Http Module that takes care of initializing and disposing the context. On Win Forms, I use the controller in MVC to take care of this (if the application is complex enough to demand this). The simplest scenario is a Windows Service. There I have some sort of coordinator that dispatch work, and it takes care of it, like this:

public void DispatchWork()

{

       IDbConnection connection = GetConnectionFromSomewhere();

       using (Context.Initialize(connection))

       {

              //Do work within this context

                }
}

I initialize the connection, and then I can do the rest of my work (usually by calling other classes who pre-condition is that the context is initialized).  I found that this approach combines both thread safety and the convenience of using static. Because there is only a single thread of execution (even if it is a logical one), there will not be surprises because of this. In the first post about statics, I gave an example of the IDbConnection blowing up because two threads access it in the same time. Using this approach, there is only a single thread, and it is consistent. If it will blow up, it will always blow up.

I may be in the middle of process an IDataReader, and call another method that tries to read from the database, this will fail immediately, since the second method will try to read and that is (generally) not allowed when a data reader is already opened. There are no surprises there, and that is very important thing.

To talk in patterns, it is a Service Locator. Personally, I find that the Context class becomes the speed dial into the rest of the application. I try to keep my context as lightweight as possible, but I put common methods there as well (see the IsAllowed() above for example of that). One thing that I insist on is that everything that the context allow access to will be mockable. Usually this mean returning an interface. When I need to test the code, I simply replace the implementation (either using the initializer or by going directly to Local.Data[] and modifying that entry).

But what about the Is Allowed method? It is a static method, and that can’t be mocked. The Is Allowed method just make a call to the security service in the Context (not shown here), and that can be mocked. In this case, it is just a short cut to make it easier to follow the Law of Demeter and to save repeating code.

There are some disadvantages, you lose the ability to look at a class’ interface and tell what the dependencies are. It may pull stuff from the context to do its work, and you will need to look at the code to understand how / where / what it does with it.

Another approach to this is the use of dependency injection. Castle’s Windsor has some very nice integration facilities for doing this, but without the need for the Context. In this project, it was not applicable because of customer’s demand.

* Just to note, in my own implementation I actually use a normal class, and extend the Context in several ways. It is all static, of course, but it is nice to know that each part of the application uses the same context consistently

 

Rhino Commons

time to read 2 min | 352 words

I made some updates to my commons library. It is just a set of utility classes that I find useful. At the moment it contains:

The thing that I use more than anything, though, is local data handling. I am pretty sure that I blog about this before, but I can't find it now.  The idea is to give you a simple hashtable of values that you can rely throughout your code. If you are working in Web context, it is using the Context.Items hash, and if you are working in a non-web context, you use a thread static hashtable.

This allows me to ignore where I am, and put stuff there that I know are private to my current logical thread of excutions.

You can find the bits here

time to read 7 min | 1218 words

I have recently created a grid that inherits from GridView, and add special processing. As part of the processing, I needed extra information about the data beyond just the list of items. I created a Bind() method that gets all the information, and handles the entire data binding scenario.

But this is not a common approach, and it is entirely possible that another developer will forget / not know that he needs to call this method  and use the following to add data to the grid:

grid.DataSource = foo;
grid.DataBind();

This would completely bypass my custom handling, and can lead to hard to discover bugs, after all, the code will look correct. In order to solve this issue, I used this approach:

[Obsolete("Use the Bind() method instead.", true)
public override object DataSource
{
    set
    {
        if(this.DesignMode==false)
    
       throw new InvalidOperationException(@"Can't use this setter.
                            You must use the Bind() method instead"
);
    }
}

I overrode just the setter for the DataSource property (something that I learned was possible only today), and added a compiler error when using this, as well as a runtime error. Both of those will direct the developer in the right path. I added the exception because the developer may call the class via is base class ,which will bypass the compiler obsolete error .

Update: Just to clarify, this is the Bind method, it does more than just

public void Bind<T>(ICollection<T> itemsToBind, ISecurable securable) { ... }

I added the bolded part to allow the control to work with the designer.

time to read 1 min | 135 words

Eber Irigoyen has a post about what should I hide?, based on advice from Code Complete 2. Eber is making the statement that the question should be reversed. What should I expose?

On the face of it, it looks like a reasonable suggestion, after all, I assume that we all accept that encapsulation is a good thing. The problem is that this completely ignore the notion of extensibility. It only give you the extensibility that you think of ahead of time. For examples of where this approach fail, just look at caching & batching in .Net. In both cases, the approach of show just what you must is used, and this make both completely useless for any scenario that you didn't think when creating the code.

time to read 1 min | 170 words

Ten Neward has posted a long post about OR/M - The Vietnam of Computer Science. The first part of this post is a Vietnam war history lesson, and I kind of missed the point, then he goes on to point at various issues with OR/M.

I don't quite get the point of the post, to tell the truth,  and I am tempted to raise Godwin's Law in this matter

He raises some valid points, but each of those issues are already mostly solved issues.

To give some examples:

  • Entity identity vs. Row Identity – Identity maps and Unit Of Work handle this issue.
  • Concurrency  - Last Write Win, Optimistic Concurrency, Explicit locking.
  • Caching across a web farm – Use a distribute cache.

time to read 3 min | 564 words

I the last week I was asked multiply times about using Rhino Mocks to mock interfaces with generic methods.

At the moment, this is not working, the code needed to generate generic methods on runtime is not trivial, and I tried fixing it several times, without success. Currently, Dynamic Proxy 2 is being worked on, which will have support for generic methods, so I expect to have this feature soon.

The following hack will get you by for now, it is not ideal, but it is what I have at the moment.

The ISession interface from NHibernate contains a generic Load<T>(object id) method, which measn that Rhino Mocks can't mock it. Here is how we solve the issue:

public abstract class SessionWithoutGenerics : ISession

{

       public override sealed Load<T>(object id)

       {

              return (T)Load(typeof(T), id);

       }

}

We basically disable the mocking of this specific method, and now we mock this class, and continue life as usual.

 

time to read 5 min | 852 words

This is not only one of the nicest logos that I have seen, it is also the logo of Rhino Mocks Boo Macros, which is a language extension for Boo that integrate Rhino Mocks directly into the language.

 

Andrew Davey released it today, and it completely blew me away.

I did some Boo hacking, and I have a fully appreciation of the scale of the task that Andrew had.

 

Check out how simple it looks:

 

[Test]

def Example():

    record mocks:

        foo as IFoo = mocks.CreateMock(IFoo)

        expect foo.Dog(int, x as string, y as int):

            x [ Is.NotNull() ]

            y [ Is.GreaterThan(0) & Is.LessThan(10) ]

            return 42.0

           

    verify mocks:

        foo.Dog(0, "hello", 5)

 

The above example creates an expectation for a call on foo.Dog(anything, not-null,  between 0 and 10), and then make the call. There is a lot more documentation here.

 

Very nice and simple to work with.

Congratulations, Andrew, and very good work.

FUTURE POSTS

  1. Goodbye Hibernating Rhinos, Hello RavenDB LTD - 9 hours from now
  2. Replacing developers with GPUs - 2 days from now
  3. Memory optimizations to reduce CPU costs - 4 days from now
  4. AI's hidden state in the execution stack - 7 days from now

There are posts all the way to Aug 18, 2025

RECENT SERIES

  1. RavenDB 7.1 (7):
    11 Jul 2025 - The Gen AI release
  2. Production postmorterm (2):
    11 Jun 2025 - The rookie server's untimely promotion
  3. Webinar (7):
    05 Jun 2025 - Think inside the database
  4. Recording (16):
    29 May 2025 - RavenDB's Upcoming Optimizations Deep Dive
  5. RavenDB News (2):
    02 May 2025 - May 2025
View all series

Syndication

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