The Inquisitive Coder – Davy Brion's Blog

Trying to walk that thin line between intelligence and ignorance

Archive for the 'Dependency Injection' Category

Inversion Of Control Containers And Factories Aren’t Mutually Exclusive

Posted by Davy Brion on 23rd January 2010

Julian Birch recently posted a reaction to my reaction to Uncle Bob’s IOC lunacy post.  Julian mistakenly thinks that i have a problem with using factories.  I definitely don’t have a problem with using factories.  I just have a problem with using them in the manner that Uncle Bob suggested in his post.  Jeffrey Palermo also recently posted an example of where he thinks using a factory is better than injecting dependencies.  I wanted to react to both those posts with a real-world example of where i prefer to use a factory and how i use an IOC container to do so.

As you probably know by now, i’m a big proponent of using IOC containers.  I’ve never stated that they should be used in every single application, but using one certainly pays off in most applications, especially as complexity increases gradually.  When you use an IOC container, you’ll have much less need for factories.   There are however two situations where i certainly prefer to use a factory.  And that is when:

  1. a certain dependency might not always be used by a class and that dependency is expensive to create
  2. i might need multiple instances of a dependency during the lifetime of a class

A good example of both those situations is when using Agatha’s AsyncRequestDispatcher class from a Silverlight user control.  Creating an AsyncRequestDispatcher is expensive because it in turn requires an instance of the AsyncRequestProcessorProxy class.  The AsyncRequestProcessorProxy class inherits from WCF’s ClientBase class, and those types are relatively expensive to create.   And due to the asynchronous nature of those service calls, you can never deterministically dispose of a AsyncRequestDispatcher instance with absolute certainty that it won’t be disposed before the response of the service call is returned from the service.  Because of that, the AsyncRequestDispatcher class was designed to dispose of itself automatically once the response is returned.  This effectively means that you’ll need a new instance of AsyncRequestDispatcher whenever you need to make an asynchronous call to an Agatha service. 

For most user controls, it obviously doesn’t make sense to inject one instance of the AsyncRequestDispatcher into the user control because you often need to make multiple service calls depending on user interactions or other events.   A good way to deal with this is obviously to ask a factory to create the AsyncRequestDispatcher whenever you need one.   Which is why Agatha offers the AsyncRequestDispatcherFactory class, which looks like this:

    public interface IAsyncRequestDispatcherFactory

    {

        IAsyncRequestDispatcher CreateAsyncRequestDispatcher();

    }

 

    public class AsyncRequestDispatcherFactory : IAsyncRequestDispatcherFactory

    {

        public IAsyncRequestDispatcher CreateAsyncRequestDispatcher()

        {

            return IoC.Container.Resolve<IAsyncRequestDispatcher>();

        }

    }

 

Now, some of you are probably thinking: what is the difference between this and Uncle Bob’s example?  Well, unlike Uncle Bob’s example this factory is not responsible for registering the required components to create an AsyncRequestDispatcher with the container.  It merely resolves an instance and returns it.  And yes, it uses the container to do so.   I could actually just new up an AsyncRequestDispatcher myself but then the factory would also have to know about its dependencies and make sure it’d be able to create them.  If those dependencies have dependencies of their own, i’m back to dealing with dependencies manually which is exactly what i’m trying to avoid throughout my codebase.

I can’t come up with a single reason why this would be wrong, but some of you probably will so feel free to point out those reasons :)

The benefit of this factory is that it enables me to delay the instantiation of an expensive dependency, and it also enables me to get more than one instance if i need to during the lifetime of a single object.  At the same time, it doesn’t have any of the downsides of Uncle Bob’s approach.  Also, this approach is something that you won’t need to resort to throughout your codebase, it’s more for edge-cases.

Now, how do we use this factory?  Instead of new’ing the factory manually like Jeffrey does in his example, the factory is registered with the IOC container and i simply inject the factory into the class that needs to use it.  This still enables me to change implementations of both the factory as well as the instances the factory needs to create.  And it also makes it easy to stub or mock the factory during tests.  I get all of the benefits from using Dependency Injection and an IOC container, and i have yet to notice any downsides to this approach.  But again, i only use this approach in the 2 situations i mentioned in the beginning of this post.  In most cases, you really don’t need factories anymore.  And when you do, just leverage your IOC container to make the factory as simple and dumb as possible.

Posted in Dependency Injection, Inversion Of Control | 10 Comments »

Dependency Injection Inversion Rejection

Posted by Davy Brion on 19th January 2010

Uncle Bob has done it again.  In his latest post, he actually advises people to go back to manual dependency injection instead of relying on a framework (our beloved IOC containers) to do it for us.  You really ought to check out the post and his examples in particular.  Done with that? Ok.

There are two major problems that i have with his post.  The first is this one:

I like this because now all the Guice is in one well understood place. I don’t have Guice all over my application. Rather, I’ve got factories that contain the Guice. Guicey factories that keep the Guice from being smeared all through my application.

What’s more, if I wanted to replace Guice with some other DI framework, I know exactly what classes would need to change, and how to change them. So I’ve kept Guice uncoupled from my application.

For those of you who don’t know, Guice is an IOC container from Google.  Uncle Bob doesn’t want references of an IOC container spread out throughout his application, but he doesn’t seem to mind coupling his factories with his IOC container for some reason.  He seems to think that he can actually switch to a different container more easily because of this, because he would only have to modify his factories.

Here’s the deal.  If you have more than a handful of references to your IOC container in your code (apart from the registration obviously), then you really don’t know what using an IOC container is all about.  Yes, i know Uncle Bob is supposed to be a legend.  Yes, i realize that i’m saying that a legend in the OO world doesn’t seem to grasp some of the most important concepts of using an IOC container.  Can you really disagree with that after reading his post?

His whole idea of making it easier to switch to another container with his approach is ludicrous.  He would have to modify every single factory that he uses, and in his trivial non-real world examples that wouldn’t be a lot to do but out here in the real world, we’d end up with a boatload of those factories and they would all have to be modified.  Conversely, if you’re using an IOC container in the way it is meant to be used, you’d only have to change your registration code and the one or two places where you resolve something manually through the container.  And that’s it.  Yes, you typically only need one or two places where you use the container directly.  Well, unless you’re Uncle Bob of course.

My other problem with his post is with the sample that he uses.  It really is a very simplistic example and the approach he outlines simply does not scale when you’re dealing with large, real-world codebases.  His approach might work for the size of the examples in his books, or for the code of Fitnesse, but if i were to apply his recommended approach for some of the systems that we’re working on, it would lead to a terrible mess very quickly.  Not exactly what i’d have in mind when thinking of Clean Code.

The one thing i do like about this post? Well, there are quite a few people who follow Uncle Bob blindly and can’t say a single bad thing about his thoughts/ideas/approaches.  I know quite a few of them make extensive use of IOC containers and some of them are even involved in the development of these containers.  Hopefully, Uncle Bob’s post will finally convince these people that blindly following anyone is simply never a good idea and that you have to keep a critical mindset for everything that you read, no matter who wrote it.

Posted in Dependency Injection, Inversion Of Control | 17 Comments »

Real World Benefits From Loose Coupling, Inversion Of Control And Dependency Injection

Posted by Davy Brion on 10th December 2009

Concepts like Dependency Injection and using an Inversion Of Control container have gradually gotten more popular and accepted in the .NET world in the last 2 years or so.  There are however still quite a few people who doubt the validity of these concepts.  Quite a few of these people seem to think that Dependency Injection for instance is only useful to increase the testability of your code. I wanted to go over a real world example which shows a (IMO) huge benefit which can be solely attributed to thinking about loose coupling, using Dependency Injection and using an Inversion Of Control container.

I recently wrote a post about how you can use an Agatha service layer fully in-process instead of having to host it in a different service through WCF.  The only reason why it’s so easy to do that, is because Agatha’s design makes heavy use of loose coupling and dependency injection.  And obviously, it makes use of an Inversion Of Control container to manage the dependencies and to wire everything together.

There are basically 3 very important parts to Agatha.  The first is the Request Processor.  This class basically delegates the handling of each incoming request to its corresponding request handler.  The other important parts are the Request Dispatcher (for synchronous client-side usage) and the Asynchronous Request Dispatcher (for asynchronous client-side usage).  I’ll just refer to these two classes as the request dispatchers for the rest of this post.  When the service layer is hosted through a WCF service, the request dispatchers need to communicate with the Request Processor through a proxy (either a synchronous one, or an asynchronous one).  It would’ve been very easy to tie the implementations of the request dispatchers directly to the implementation of the WCF proxies.  If i had gone that way, i wouldn’t have been able to offer the ability to run the service layer in process though, since the request dispatchers would require the WCF proxies to be used.  I could’ve hosted the WCF service in process, but that would really be overkill if you don’t really want to use WCF.

As easy as it would’ve been to tie the request dispatchers directly to the proxies, it was just as easy to make them depend on a slightly more abstract component.  There are two interfaces to communicate with the Request Processor:

    public interface IRequestProcessor : IDisposable

    {

        Response[] Process(params Request[] requests);

        void ProcessOneWayRequests(params OneWayRequest[] requests);

    }

 

    public interface IAsyncRequestProcessor : IDisposable

    {

        IAsyncResult BeginProcessRequests(Request[] requests, AsyncCallback callback, object asyncState);

        Response[] EndProcessRequests(IAsyncResult result);

        void ProcessRequestsAsync(Request[] requests, Action<ProcessRequestsAsyncCompletedArgs> processCompleted);

 

        IAsyncResult BeginProcessOneWayRequests(OneWayRequest[] requests, AsyncCallback callback, object asyncState);

        void EndProcessOneWayRequests(IAsyncResult result);

        void ProcessOneWayRequestsAsync(OneWayRequest[] requests, Action<AsyncCompletedEventArgs> processCompleted);

    }

 

Notice that there are no WCF attributes on these interfaces.  I have two more WCF-enabled interfaces, namely the IWcfRequestProcessor and the IAsyncWcfRequestProcessor.  They define the same methods as their non-WCF counterparts, but have all of the required WCF attributes placed on top of those methods.

Typically when creating (or generating) a WCF proxy, the proxy will only implement the interface of the service contract (in this case, that would be the IWcfRequestProcessor or the IAsyncWcfRequestProcessor interface).  Any class that would want to use these proxies would then need an instance of that proxy to be able to communicate with the WCF service.  In Agatha’s proxies, i chose a slightly different approach.  They implement both the WCF interface as well as the none-WCF interface.  Since the method definitions are identical, this doesn’t require any more work.  Take a look at the class definitions of those proxies:

    public class RequestProcessorProxy : ClientBase<IWcfRequestProcessor>, IRequestProcessor

    public class AsyncRequestProcessorProxy : ClientBase<IAsyncWcfRequestProcessor>, IAsyncRequestProcessor

 

As you can see, both proxy classes inherit from WCF’s ClientBase class and pass the WCF-specific interface as the generic type parameter to ClientBase.  That means that these proxies can execute the WCF operations defined in the WCF-specific interface.   These proxy classes also implement the original interfaces, which means that these proxies can be used by any class which requires an instance of IRequestProcessor and IAsyncRequestProcessor.

In Agatha, there is no class that directly uses either the RequestProcessorProxy or the AsyncRequestProcessorProxy class.  Instead, the request dispatchers depend solely on IRequestProcessor or IAsyncRequestProcessor:

        public RequestDispatcher(IRequestProcessor requestProcessor)

        public AsyncRequestDispatcher(IAsyncRequestProcessor requestProcessor)

 

The dispatchers never know exactly who they’re talking to.  This means that they can communicate either through a WCF proxy, or the real Request Processor, depending on how your Inversion Of Control container is configured.

That is a huge benefit because it gives you a tremendous amount of flexibility when it comes to how you want to use your service layer (in process, in another service, on another machine, whatever) and it really didn’t take any extra effort with regards to development time to achieve that flexibility.  If i want to use Agatha with a different communication technology, then i could do so by simply creating implementations of the IRequestProcessor and IAsyncRequestProcessor interfaces which deal with the specifics of whatever that different communication technology might be.  I would also have to change the way the implementations are registered with the Inversion Of Control container to make sure that the new implementations are used.  But i wouldn’t have to change anything else.

In this case, dependency injection and loose coupling was not used to increase testability.  The increased testability that comes from using this approach is an added bonus.

Posted in Code Quality, Dependency Injection, Inversion Of Control, Patterns | 5 Comments »

Constructor Injection vs Setter Injection

Posted by Davy Brion on 2nd November 2009

For those of you who’ve used Dependency Injection, you know that the two most common ways of injecting a dependency into a class are constructor injection and setter injection. For those of you who haven’t used Dependency Injection yet, here’s a simple example which shows both techniques:

    public class MyService : IMyService

    {

        private IRequiredDependency requiredDependency;

 

        public IOptionalDependency OptionalDependency { get; set; }

 

        public MyService(IRequiredDependency requiredDependency)

        {

            this.requiredDependency = requiredDependency;

        }

 

        public void DoSomething()

        {

            // do something cool and/or important

            // ...

        }

    }

This example is very abstract, but it should be pretty clear. Constructor injection is used to inject the required dependency whenever an instance of MyService is created, whereas setter injection is used to inject the optional dependency after the instance is created. I obviously can’t speak for everyone who uses Dependency Injection, but generally speaking most people use constructor injection for required dependencies and setter injection for optional dependencies.

There is however one situation in which i prefer setter injection for required dependencies over constructor injection: dependencies of abstract classes or base classes. For instance, in our service layer each incoming request is handled by a specific RequestHandler. Most of our RequestHandlers need our NHibernate infrastructure to be set up, which is automatically taken care of by our UnitOfWork implementation. So we have the following NhRequestHandler class (simplified for the purpose of this blog post):

    public abstract class NhRequestHandler<TRequest, TResponse> : RequestHandler<TRequest, TResponse>

        where TRequest : Request

        where TResponse : Response

    {

        public IUnitOfWork UnitOfWork { get; set; }

 

        public override Response Handle(Request request)

        {

            using (ITransaction transaction = UnitOfWork.CreateTransaction())

            {

                Response response;

 

                try

                {

                    response = base.Handle(request); // calls the specific Handle(TRequest) method of the derived handler

                    transaction.Commit();

                }

                catch (Exception e)

                {

                    transaction.Rollback();

                    throw;

                }

 

                return response;

            }

        }

    }

As you can see, the IUnitOfWork dependency is a required dependency because you would get a NullReferenceException when trying to handle a request without having a IUnitOfWork instance present. Yet, i really don’t want to put it in the constructor because then each and every RequestHandler that derives from this will also have to put it in the constructor, even though most of them won’t access the IUnitOfWork directly.

Actually, most of our applications inherit from the NhRequestHandler and then add some more dependencies that some kind of base BusinessRequestHandler will need. These are dependencies to deal with authentication, authorization, user context, application context, etc… Some of these dependencies will be used by the derived RequestHandlers, some won’t. All of them however will indeed be used by the BusinessRequestHandler so they are definitely required dependencies. Using constructor injection for these dependencies would lead to ‘noise’ in every derived RequestHandler’s constructor.

Instead, we use setter injection for all of a base-type’s dependencies, and use constructor injection only for the dependencies of the derived types. It keeps the constructors as clean as they can be and avoids unnecessary noise. We know that our IOC container will fulfill all the constructor dependencies as well as each property dependency in the inheritance hierarchy so there’s no chance of anything going wrong there. Unless of course somebody seriously breaks the IOC configuration but in that case, our applications won’t even make it through the simplest of requests so that’s not something that will ever happen unnoticed.

And for our tests, we always inherit our fixtures from things like HandlerTest or ControllerTest or whatever where all of those property dependencies are automatically set up with mocks or stubs, so it doesn’t really cause problems there either.

Posted in Dependency Injection | 12 Comments »

Managing your NHibernate Sessions

Posted by Davy Brion on 22nd June 2008

Note: you can find a more recent post on this concept here.

I was working on my northwind sample application (which i’ll post about as soon as i get something that’s worth showing) and i was struggling to find a clean way to manage my NHibernate sessions. I wanted a way to create a session once you enter the service layer, and that session should be available transparently to the repository implementations without actually having to constantly pass it around. But i didn’t just want to store it somewhere and have all the classes that needed the current session get it directly from that place. Also, i didn’t want the current session to be available to everyone. Another important requirement was to have maximum flexibility for writing tests. I could just use Rhino-Commons’ implementations of the UnitOfWork and Repository patterns and be done with it, but where’s the fun in that? And since this application is mostly a learning experience i figured i should try to write this myself. After a bit of searching and experimenting, i finally came up with a way that i’m happy with (for now anyways). Let’s have a look.

To illustrate what i want, take a look at this made-up method in my service layer:

        public ProductCategoryDTO[] GetAllProductCategories()

        {

            using (ISession session = GetNewSession())

            {

                var repository = GetProductCategoryRepository();

                var categories = repository.GetAllProductCategories();

                return categories.ToDTOs();

            }

        }

This is just some example code, it doesn’t even work. But it’s kinda what i want… The thing is, i don’t want to deal directly with the ISession type in the service layer, but i do want the ProductCategoryRepository to use the ISession that is created within the context of this method call.

NHibernate’s ISession type is an implementation of the Unit Of Work pattern. I don’t want to use the ISession directly in my service layer because i want something that is a bit more high-level. Basically just something that would allow me to work within an NHibernate session, and provide me with the ability to flush changes to the database whenever i want to. And obviously, i want it to allow me to create a transaction as well. So i came up with the following unit of work interface:

    public interface IUnitOfWork : IDisposable

    {

        /// <summary>

        /// Flushes any changes that haven't been executed yet

        /// </summary>

        void Flush();

 

        /// <summary>

        /// Creates an ITransaction instance with the ReadCommitted isolation level

        /// </summary>

        /// <returns></returns>

        ITransaction CreateTransaction();

 

        /// <summary>

        /// Creates an ITransaction instance with the given isolation level

        /// </summary>

        /// <param name="isolationLevel"></param>

        /// <returns></returns>

        ITransaction CreateTransaction(IsolationLevel isolationLevel);

    }

This interface pretty much offers me anything i’m concerned with in my service layer. The real implementation would do a bit more though… It has to create an NHibernate session and make it available to the repositories in a clean way. Here’s the thing though… the repositories have a completely different lifetime than the NHibernate sessions. The NHibernate session has to be created when we enter a service method, and it has to be valid within the scope and context of the execution of that service method. The repositories however stay alive for the lifetime of the application so they can’t just hold a reference to an NHibernate session. Every time you call a method of a repository, it has to find out which session it should use, which is the session that is being used in the context of the current service method call. Now, we could always pass around the session but that really doesn’t look good and is cumbersome. So i basically need something that gives me access to the active nhibernate session:

    public interface IActiveSessionManager

    {

        /// <summary>

        /// Returns the active ISession for the current thread. Throws exception if there's

        /// no active ISession instance

        /// </summary>

        /// <returns></returns>

        ISession GetActiveSession();

 

        /// <summary>

        /// Sets the active ISession for the current thread. Throws exception if there's

        /// already an active ISession instance

        /// </summary>

        /// <param name="session"></param>

        void SetActiveSession(ISession session);

 

        /// <summary>

        /// Clears the active ISession for the current thread.

        /// </summary>

        void ClearActiveSession();

    }

That gives me the ability to retrieve and set the active session on a per-thread basis. After all, a service method call will be handled by one thread, so setting the active session for that current thread is a convenient way to store the session.

Now i still need something that takes care of creating the NHibernate sessions:

    public interface ISessionFactory

    {

        /// <summary>

        /// Creates a new ISession instance

        /// </summary>

        /// <returns></returns>

        ISession Create();

    }

Ok, so what do we have so far? An interface to define the functionality that a UnitOfWork should offer at the service level. An interface to store/retrieve the active session on the current thread, and finally, an interface to actually create the NHibernate session. Let’s start looking at the real implementations. Here’s the code to the SessionFactory class:

    public class SessionFactory : ISessionFactory

    {

        private readonly NHibernate.ISessionFactory sessionFactory;

 

        public SessionFactory()

        {

            Configuration configuration = new Configuration()

                .Configure()

                .AddAssembly("Northwind");

 

            sessionFactory = configuration.BuildSessionFactory();

        }

 

        public ISession Create()

        {

            return sessionFactory.OpenSession();

        }

    }

Pretty straightforward… it initializes NHibernate and gives us the ability to ask for new sessions. So how are we going to make these sessions available to our repositories? Through the ActiveSessionManager class of course:

    public class ActiveSessionManager : IActiveSessionManager

    {

        [ThreadStatic]

        private static ISession current;

 

        public ISession GetActiveSession()

        {

            if (current == null)

            {

                throw new InvalidOperationException("There is no active ISession instance for this thread");

            }

 

            return current;

        }

 

        public void SetActiveSession(ISession session)

        {

            if (current != null)

            {

                throw new InvalidOperationException("There is already an active ISession instance for this thread");

            }

 

            current = session;

        }

 

        public void ClearActiveSession()

        {

            current = null;

        }

    }

It basically just stores the session in a ThreadStatic field, which means that each thread will have a different static reference for this field. So if we set the active session through the SetActiveSession method in thread X, and thread Y also sets an active session, the GetActiveSession method will return the correct session instances for each thread.

So now we have everything we need to create our UnitOfWork class:

    public class UnitOfWork : Disposable, IUnitOfWork

    {

        private readonly IActiveSessionManager activeSessionManager;

        private readonly ISession session;

 

        public UnitOfWork(ISessionFactory sessionFactory, IActiveSessionManager activeSessionManager)

        {

            this.activeSessionManager = activeSessionManager;

            session = sessionFactory.Create();

            activeSessionManager.SetActiveSession(session);

        }

 

        protected override void DisposeObjects()

        {

            if (session != null)

            {

                session.Close();

                session.Dispose();

            }

        }

 

        protected override void ClearReferences()

        {

            activeSessionManager.ClearActiveSession();

        }

 

        public void Flush()

        {

            session.Flush();

        }

 

        public ITransaction CreateTransaction()

        {

            return CreateTransaction(IsolationLevel.ReadCommitted);

        }

 

        public ITransaction CreateTransaction(IsolationLevel isolationLevel)

        {

            return session.BeginTransaction(isolationLevel);

        }

    }

When the UnitOfWork is created, it receives an ISessionFactory instance, and an IActiveSessionManager instance. It then creates a new session through the ISessionFactory and uses the IActiveSessionManager to make sure that session is the active session for the current thread. When the UnitOfWork is disposed, it closes and cleans up the session and it also uses the IActiveSessionManager to clear the active session for the current thread. Oh and it obviously also provides implementations for what it is we actually need in our service layer: flushing the changes whenever we want and creating transactions.

The ISessionFactory and IActiveSessionManager instances should stay alive as long as the application is alive. But as you could see in the implementations of those types, we didn’t write any code to deal with their lifetimes. I’m actually relying on my IoC container for that. In the class where my container is set up, you’ll find the following code:

        private static void RegisterUnitOfWorkComponents()

        {

            Register(Component.For<ISessionFactory>()

                .ImplementedBy<SessionFactory>().LifeStyle.Singleton);

            Register(Component.For<IActiveSessionManager>()

                .ImplementedBy<ActiveSessionManager>().LifeStyle.Singleton);

            Register(Component.For<IUnitOfWork>()

                .ImplementedBy<UnitOfWork>().LifeStyle.Transient);

        }

ISessionFactory and IActiveSessionManager are registered as singleton instances, so whenever these types are requested, the same instances will be returned. The IUnitOfWork type is registered with a transient lifetime, so whenever it is requested, the container will create a new UnitOfWork class and pass the ISessionFactory and IActiveSessionManager instances to the constructor.

Right, we’ve taken care of creating the session, associating it with the current thread and making it available in a nice and clean way. Now we actually have to make sure our repositories can use it. In the base repository implementation, you can find the following code:

        private readonly IActiveSessionManager activeSessionManager;

 

        public Repository(IActiveSessionManager activeSessionManager)

        {

            this.activeSessionManager = activeSessionManager;

        }

 

        protected ISession Session

        {

            get { return activeSessionManager.GetActiveSession(); }

        }

Whenever a repository needs a session, it just needs to use the protected Session property and it will get the session that is associated with the current thread.

So now we can rewrite our made-up service method from earlier to the following:

        public ProductCategoryDTO[] GetAllProductCategories()

        {

            using (Container.Resolve<IUnitOfWork>())

            {

                var repository = Container.Resolve<ProductCategoryRepository>();

                var categories = repository.GetAllProductCategories();

                return categories.ToDTOs();

            }

        }

We know that the NHibernate session will be created, and more importantly, that it is not just globally accessible to everyone. It can only be accessed when you have a reference to an IActiveSessionManager instance. We also don’t need to pass around the session all the time so our code is a bit more concise, showing only the intent of what we’re trying to do without distracting us with details that are not relevant to that intent. We also have a lot of flexibility to write tests… i can write tests for my repositories without having to create a UnitOfWork… i can simply pass a fake IActiveSessionManager to my repositories when i’m testing them and have it return the session that i’m using for my test. All in all, this approach offers me with a lot of advantages, without ugly disadvantages. Well, at this moment i don’t really see any disadvantages so if you do see some, please let me know :)

Posted in Dependency Injection, Inversion Of Control, NHibernate, Patterns | 35 Comments »

Automanual Dependency Injection?

Posted by Davy Brion on 16th June 2008

I apologize in advance for using the term ‘automanual’ but if you’ve been reading this blog for a while you already know i completely suck at coming up with good names. So bear with me, and you’ll probably understand what i mean as you work your way through this post. It really is pretty cool… i promise :p

I’m playing around with some supervising controller MVP stuff using regular ASP.NET webforms. Yes i know, i should be using ASP.NET MVC but i have a strict “i don’t touch it before there’s a final release”-policy when it comes to Microsoft products (as opposed to my “lemme just build the latest version of the trunk”-policy for various open source products). Anyways, what i’m trying to do is pretty simple. I have a view (ProductList.aspx) which uses a supervising controller (ProductListController). The view (the aspx page) will notify the controller when it needs to do something through events. The controller will then do whatever it needs to do and it will send the data back to the view through properties of the view. If that’s not clear to you, read the post i linked to for a much better and detailed explanation.

Since ASP.NET automatically instantiates your aspx page, the easiest thing to do is to let the view create the controller and then pass itself as a parameter to the controller. But the controller also has other dependencies, such as a service which exposes the business logic that we need for this screen. So i have two options: i either create the controller myself and provide all the dependencies, or i use an inversion of control container to create the controller and to wire up all the dependencies. I don’t want to have to modify my view code whenever i add/remove a dependency of the controller, so i go with the inversion of control container.

Suppose the constructor of the controller looks like this:

        public ProductListController(IProductList view, IProductsService productsService)

        {

            this.view = view;

            this.productsService = productsService;

        }

Here’s where it gets tricky… since the view (which implements the IProductList interface) is asking the container to create a ProductListController, how can the container pass the correct IProductList dependency to the controller? We can’t use the regular dependency look-up mechanisms because our controller actually needs the current view instance, but that view instance is asking the container to create the controller! By default, the container has no way whatsoever to resolve the IProductList dependency to the current view instance. So basically, what we want to do in this case is to manually provide the view dependency, but still have the container automatically provide the IProductsService dependency (hence the term ‘automanual’ which you have to admit is starting to sound pretty good at this point, right?). And of course, we want all of this to work automagically.

It turns out that Castle’s Windsor actually does have some slick tricks to make this work. Here’s how we can create the controller through the container from the view:

            IProductListController controller =

                Container.Resolve<IProductListController>(new { view = this });

Told you it was slick! It’s pretty easy actually… the parameter we pass to the Resolve method is an instance of an anonymous type with a view property. We set the view property to the current aspx instance (using the ‘this’ keyword obviously) and Windsor is smart enough to figure out that this value should be used to satisfy the view dependency instead of using it’s normal look-up mechanisms. The result is that our controller has a reference to the current view, and its IProductsService reference is resolved as the container would typically resolve dependencies. Pretty sweet.

Btw, i googled the term ‘automanual’ and sure enough, it already exists… but it’s not really used in the context of writing code so if this thing sticks, remember where you heard it first ;)

Posted in ASP.NET, Castle Windsor, Dependency Injection, Inversion Of Control | 3 Comments »

Windsor’s Interceptors and Performance, Part 2

Posted by Davy Brion on 10th May 2008

Gael Fraiteur’s comment on my previous post made me realize that my performance test in the previous post wasn’t all that good…

Let’s go back to the part of the code that performed the test:

        [Test]

        public void TestDummyPerformance()

        {

            Time(() => CallMethodXAmountOfTimes(new Dummy(), 1000000));

            Time(() => CallMethodXAmountOfTimes(Container.Resolve<IDummy>(), 1000000));

        }

 

        private void CallMethodXAmountOfTimes(IDummy dummy, int times)

        {

            for (int i = 0; i < times; i++)

            {

                dummy.DoSomething();   

            }

        }

 

        private void Time(Action action)

        {

            DateTime before = DateTime.Now;

            action();

            Console.WriteLine("Time elapsed : " + (DateTime.Now - before));

        }

The Time method has an Action parameter, which basically points to a block of code that will be executed when you call it. In this case the action() line causes the block of code to be executed. I have a habit of trying to write concise code, so the instantiation of the dummy instance is in both cases inlined in the block of code that will be executed by the Time() method. As Gael points out in his comment, Windsor generates a proxy when you request a component that has an interceptor assigned to it, and this is obviously a more expensive operation than simply new-ing a concrete instance. So this extra cost was reflected in the results as well.

If we change the test code to this:

        [Test]

        public void TestDummyPerformance()

        {

            var dummy = new Dummy();

            Time(() => CallMethodXAmountOfTimes(dummy, 1000000));

            var interceptedDummy = Container.Resolve<IDummy>();

            Time(() => CallMethodXAmountOfTimes(interceptedDummy, 1000000));

        }

Now, the difference is not so big as it was in the previous test:
Time elapsed : 00:00:00.0100144
Time elapsed : 00:00:00.2403456

Again, this is for one million method calls… in a real world scenario, you probably won’t notice the performance hit.

Tags: ,
Posted in Castle Windsor, Dependency Injection, Inversion Of Control, Software Development | No Comments »

Adding behavior without modifying existing code with Windsor

Posted by Davy Brion on 4th May 2008

The Windsor container makes it quite easy to add behavior to components, without having to modify their implementation. This could be useful in many scenario’s. Suppose you need to log whenever a method from our OrderRepository class is called. But we should be able to turn the logging on and off whenever we want. Preferably, without having to modify the code all the time. Now, you could easily write a logger class that checks for a configuration setting and only logs when needed. This approach would definitely work. But then there’s logging code all over the OrderRepository class and in most cases, it’s not even necessary since they only want to be able to log under certain circumstances. Should the OrderRepository class really care about the logging? Why litter the code with logging statements?

If you’re using the Windsor container, you could easily add logging behavior to the OrderRepository class without having to change any of the existing code. Windsor has this concept of Interceptors. Basically you can assign an interceptor to any component and you can plug in your custom behavior when the component is called. Lets get into an example… Since logging is such a common requirement, we decided to put it in one class instead of littering our entire code base with logging statements. So we wrote the following class:

    public class LoggingInterceptor : Castle.Core.Interceptor.IInterceptor

    {

        private readonly ILogger logger;

 

        public LoggingInterceptor(ILogger logger)

        {

            this.logger = logger;

        }

 

        public void Intercept(IInvocation invocation)

        {

            string methodName =

                invocation.TargetType.FullName + “.” + invocation.GetConcreteMethod().Name;

            Log(“Entering method: “ + methodName);

            invocation.Proceed();

            Log(“Leaving mehod: “ + methodName);

        }

 

        private void Log(string line)

        {

            logger.WriteLine(DateTime.Now.TimeOfDay + ” “ + line);

        }

    }

This class implements the IInterceptor interface by implementing the Intercept method. When that method is called we simply construct the full method name, log when we enter the method, call the original method and then we log again when we leave the method. Nothing more, nothing less. Also notice how the LoggingInterceptor has a dependency on an ILogger instance. That instance will be injected by the container as well.

So first of all, we need to define the ILogger and LoggingInterceptor components:

      <component id=ILogger service=Components.ILogger, Components

                type=Components.Logger, Components />

 

      <component id=LoggingInterceptor service=Components.LoggingInterceptor, Components

                type=Components.LoggingInterceptor, Components

                lifestyle=transient />

Right… so now we need to add this behavior to the OrderRepository class. This only requires modifying the registration of the IOrderRepository component:

      <component id=IOrderRepository

                service=Components.IOrderRepository, Components

                type=Components.OrderRepository, Components>

 

        <interceptors>

          <interceptor>${LoggingInterceptor}</interceptor>

        </interceptors>

 

      </component>

What we basically did was tell Windsor that whenever an IOrderRepository is requested, we should return an instance of OrderRepository and each time a method of that instance is called, it needs to be intercepted by our LoggingInterceptor.

So if we simply call the IOrderRepository methods like this (obviously these are dummy calls without real parameters and we’re also ignoring return values):

            var repository = Container.Resolve<IOrderRepository>();

 

            repository.GetAll();

            repository.FindOne(new Criteria());

            repository.FindMany(new Criteria());

            repository.GetById(Guid.Empty);

            repository.Store(null);

The following output is logged:

21:53:42.6942016 Entering method: Components.OrderRepository.GetAll
21:53:42.6942016 Leaving mehod: Components.OrderRepository.GetAll
21:53:42.6942016 Entering method: Components.OrderRepository.FindOne
21:53:42.6942016 Leaving mehod: Components.OrderRepository.FindOne
21:53:42.6942016 Entering method: Components.OrderRepository.FindMany
21:53:42.6942016 Leaving mehod: Components.OrderRepository.FindMany
21:53:42.7042160 Entering method: Components.OrderRepository.GetById
21:53:42.7042160 Leaving mehod: Components.OrderRepository.GetById
21:53:42.7042160 Entering method: Components.OrderRepository.Store
21:53:42.7042160 Leaving mehod: Components.OrderRepository.Store

And we didn’t have to change the OrderRepository implementation. In fact, we can use our LoggingInterceptor wherever we like, as long as the component to be logged is registered with Windsor. And we can easily switch between logging or no logging by switching config files.

Obviously, this was just a really simple example but i hope you realize how powerful this technique is and how far you can go with this.

Tags: ,
Posted in Aspect Oriented Programming, Castle Windsor, Dependency Injection, Inversion Of Control, Software Development | 1 Comment »

Providing configuration data with Windsor

Posted by Davy Brion on 2nd May 2008

Some classes need configuration data to function properly. This configuration data could be a database connection string, a path, a hostname, a network port, whatever. You typically deal with this by putting the configuration data in your app.config or web.config… either through a Settings file or in the AppSettings or maybe you’ve created your own configuration section or whatever. And in most cases, when a class needs this data, it simply retrieves it from the Configuration class or the class that was created through your Settings class.

By doing this, you actually create a strong dependency between your class, and the object that provides the configuration data. But you’re not really dependent on the object providing the data, since you really only need a bit of data to function. So why not treat the data itself as a dependency?

Let’s use our previous example. The OrderDataAccessor class will retrieve Orders from a database. In order to do that, it needs a connection string. Instead of letting the OrderDataAccessor class retrieve that connection string from a config file itself, we’ll modify the constructor so that each instance retrieves the connection string when it is created:

        private readonly string _connectionString;

 

        public OrderDataAccessor(string connectionString)

        {

            _connectionString = connectionString;

        }

If the container now needs to create an OrderDataAccessor instance, we get the following exception:

Castle.MicroKernel.Resolvers.DependencyResolverException : Could not resolve non-optional
dependency for 'Components.OrderDataAccessor' (Components.OrderDataAccessor).
Parameter 'connectionString' type 'System.String'

Which makes sense, since we haven’t told the container about this ‘dependency’ yet. Since we’re dealing with configuration data now, it’s probably better to move our Windsor configuration to a config file as well. First we’ll define the castle configuration section in our app.config:

  <configSections>

    <section name=castle type=Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor />

  </configSections>

Then we configure our components:

  <castle>

    <components>

      <component id=IOrderDataAccessor

          service=Components.IOrderDataAccessor, Components

          type=Components.OrderDataAccessor, Components>

 

        <parameters>

          <connectionString>myConnectionString</connectionString>

        </parameters>

 

      </component>

 

      <component id=IOrderRepository

                service=Components.IOrderRepository, Components

                type=Components.OrderRepository, Components />

 

    </components>

 

  </castle>

And that’s it… Whenever the container instantiates an OrderDataAccessor instance, it will pass ‘myConnectionString’ to the connectionString parameter.

There’s one issue with this though… In a real system, you’d have more than one DataAccessor class, and having to specify the connectionString for each one of them would be a prime example of suckage. So let’s modify our config file a little bit:

  <castle>

 

    <properties>

      <connectionString>myConnectionString</connectionString>

    </properties>

 

    <components>

      <component id=IOrderDataAccessor

          service=Components.IOrderDataAccessor, Components

          type=Components.OrderDataAccessor, Components>

 

        <parameters>

          <connectionString>#{connectionString}</connectionString>

        </parameters>

 

      </component>

 

      <component id=IOrderRepository

                service=Components.IOrderRepository, Components

                type=Components.OrderRepository, Components />

 

    </components>

 

  </castle>

That’s better… Now we can just refer to the connectionString whenever we need it so we’d only have to modify it in one place.

Keep in mind that if you put the Windsor configuration in your app.config/web.config file, you need to instantiate the container like this:

            _container = new WindsorContainer(new XmlInterpreter());

So as you can see, you can also use the IoC container to keep dependencies on configuration-providing-classes completely out of your code by ‘promoting’ the required configuration data to actual dependencies of your components.

Tags: ,
Posted in Castle Windsor, Dependency Injection, Inversion Of Control, Software Development | No Comments »

Windsor and component instance lifetimes

Posted by Davy Brion on 1st May 2008

In my previous Windsor post i showed you how you can use the Windsor container to manage your components and their dependencies. Since it was merely an introductory post on Windsor, i only showed how you can use it to handle dependencies. But there’s a lot more you can do with it, and that you should know about.

One thing you’ll definitely need to know to properly use Windsor, is that of component instance lifetimes. After all, you want the container to manage your components and their dependencies. But there’s more to the management of components than merely filling in dependencies. Should the container return a new instance of a component? Should it return an already existing instance? How do you control that behavior without having clients know about it? After all, should clients of components really know about that? Is that not an implementation detail that might be better of being properly encapsulated from clients?

Windsor allows you to register components with specific lifestyles. These are the lifestyles you can use:

  • Singleton: components are instantiated once, and shared between all clients
  • Transient: components are created on demand
  • PerWebRequest: components are created once per Http Request
  • Thread: components have a unique instance per thread
  • Pooled: Optimization of transient components that keeps instance in a pool instead of always creating them
  • Custom: allows you to specify a custom lifestyle… you’d have to specify a type that implements the ILifeStyleManager interface

The Singleton lifestyle is actually the default. I’m not so happy with that being the default, but oh well… If we continue with our previous sample, we can verify that Singleton is indeed the default lifestyle for a registered component. Suppose the component is registered like this:

            _container.AddComponent<IOrderRepository, OrderRepository>();

Then the following test would pass:

            var r1 = Container.Resolve<IOrderRepository>();

            var r2 = Container.Resolve<IOrderRepository>();

 

            Assert.That(ReferenceEquals(r1, r2));

But if we change the registration to this:

            _container.AddComponentWithLifestyle<IOrderRepository, OrderRepository>(LifestyleType.Transient);

Then the test obviously fails because both requests to get an IOrderRepository instance will create a new OrderRepository instance.

You might be wondering what happens when you define a component as a singleton, but one of its dependencies is transient:

            _container.AddComponentWithLifestyle<IOrderDataAccessor, OrderDataAccessor>(LifestyleType.Transient);

            _container.AddComponentWithLifestyle<IOrderRepository, OrderRepository>(LifestyleType.Singleton);

The answer is pretty straightforward: when you request an instance of type IOrderRepository the first time, it will create a new IOrderAccessor instance as well and pass it to the OrderRepository constructor. The second time you request an instance of type IOrderRepository, the container already has the singleton instance cached, so a new IOrderAccessor instance is not created.

If you really want this behavior (a new IOrderDataAccessor instance whenever the singleton IOrderRepository is requested) you can get it working pretty easily. Right now, our OrderRepository implementation uses Constructor Injection:

        private IOrderDataAccessor _accessor;

 

        public OrderRepository(IOrderDataAccessor accessor)

        {

            _accessor = accessor;

        }

If we add Setter Injection as well the container will use the setter injector when we request the IOrderRepository instance after it has already been created:

        public IOrderDataAccessor DataAccessor

        {

            set { _accessor = value; }

        }

Because we have both Constructor Injection and Setter Injection, the container will supply a new IOrderDataAccessor when the OrderRepository instance is created. And when it is requested again after its creation, the container will supply a new IOrderDataAccessor instance to the OrderRepository using the setter of the dependency.

It’s nice to know that this is possible, but i wouldn’t recommend this approach… It’s very confusing and would certainly cause problems in multi-threaded scenarios. You’re better off injecting an IOrderDataAccessorFactory object when the repository is created, and then let the repository request a new IOrderDataAccessor instance to be used locally whenever it’s needed (as in: as a local variable during method execution, but certainly not as a field of the class).

There’s also the other way around of course… suppose the dependency is configured as a singleton, and the component to be used is configured to have the Transient lifestyle. The singleton dependency will only be created once, and every time you request a transient component that is dependent on a singleton component, the container injects the singleton instance in the transient component.

By now, I hope you realize that an Inversion Of Control Container is about more than merely Dependency Injection and increasing testability. There’s most certainly a lot more to it than that :) . I have a few more posts coming up about how using an IoC container can make your life as a developer easier.

Tags: ,
Posted in Castle Windsor, Dependency Injection, Inversion Of Control, Software Development | 1 Comment »