IoC

Why I released Windsor?

Because getting kicked that many times will hurt:

posted @ Friday, May 08, 2009 12:56 AM | Feedback (7)

Castle Windsor 2.0 RTM Released

Some would say that it is about time, I would agree. Windsor might not be the OSS project in pre release state for the longest time (I think that the honor belong to Hurd), but it spent enough time at that state to at least deserve a honorary mention. That was mostly because, although Windsor was production ready for the last three or four years or so, most of the people making use of it were happy to make use of the trunk version. If you will look, you won’t find Windsor 1.0, only release candidates for...

posted @ Tuesday, May 05, 2009 1:22 AM | Feedback (33)

MEF & Open Generic Types

I read Glenn' s post about MEF's not supporting open generic types with somewhat resembling shock. The idea that it isn't supporting this never even crossed my mind, it was a given that this is a mandatory feature for any container in the .NET land. Just to give you an idea, what this means is that you can't register Repository<T> and then resolve Repository<Order>. In 2006, I wrote an article for MSDN detailing what has since became a very common use of this pattern. Generic specialization is not something that I would consider optional, it is one of the most common...

posted @ Sunday, March 22, 2009 7:00 PM | Feedback (3)

Didja know? Merging Windsor configuration with automatic registration

One of the most annoying things that we have to do during development is updating configuration files. That is why convention over configuration is such a successful concept. The problem is what to do when you can mostly use the convention, but need to supply configuration values as well. Well, one of the nice things about Windsor is the ability to merge several sources of information transparently. Given this configuration: <configuration> <configSections> <section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor" /> </configSections> <castle> <facilities> <facility id="rhino.esb" > <bus threadCount="1" numberOfRetries="5" endpoint="msmq://localhost/demo.backend" /> <messages> </messages> </facility> </facilities> <components> <component id="Demo.Backend.SendEmailConsumer"> <parameters> <host>smtp.gmail.com</host> <port>587</port> <password>*****</password> <username>*****@ayende.com</username> <enableSsl>true</enableSsl> <from>*****@ayende.com</from> <fromDisplayName>Something</fromDisplayName> </parameters> </component> </components> </castle> </configuration> And this auto registration: var container = new WindsorContainer(new...

posted @ Wednesday, December 31, 2008 8:35 PM | Feedback (6)

First Steps with Post Sharp

PostSharp is an AOP framework that works using byte code weaving. That is, it re-writes your IL to add behaviors to it. From my point of view, it is like having the cake (interception, byte code weaving) and eating it (I haven't even looked at the PostSharp source code, just used the binary release). My initial spike with it went very well. Here it is: [Serializable] public class Logger : OnFieldAccessAspect { public override void OnGetValue(FieldAccessEventArgs eventArgs) { Console.WriteLine(eventArgs.InstanceTag); Console.WriteLine("get value"); ...

posted @ Thursday, October 09, 2008 7:52 PM | Feedback (10)

Windsor - IModelInterceptersSelector

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> ...

posted @ Sunday, October 05, 2008 3:43 PM | Feedback (9)

Windsor - IHandlerSelector

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...

posted @ Sunday, October 05, 2008 3:33 PM | Feedback (4)

Components, Implementations and Contextual Decisions

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...

posted @ Sunday, October 05, 2008 3:10 PM | Feedback (0)

The Common Service Locator library

Glenn and Chris has already gotten the word out, but that is an important piece of news. The idea is based off a post that Jeremy Miller had about a month ago, having a common, shared interface across several IoC implementation. That would allow library authors to make use of the benefits of a container without taking a dependency on a particular implementation. The alternative for that is to each library to create its own abstraction layer. A good example of that is NServiceBus' IBuilder interface, or ASP.NET MVC's IControllerFactory. That is just annoying, especially if you are integrating more than a...

posted @ Thursday, October 02, 2008 9:49 PM | Feedback (20)

The Managed Extensibility Framework

The Managed Extensibility Framework is "new library in .NET that enables greater reuse of applications and components. Using MEF, .NET applications can make the shift from being statically compiled to dynamically composed. If you are building extensible applications, extensible frameworks and application extensions, then MEF is for you." (I was too lazy to think about my own description for it, so I just copied the official one.) Probably the first thing that you should know about MEF is what will undoubtedly be the most common cause for confusion. The Managed Extensibility Framework is not an IoC container. This...

posted @ Thursday, September 25, 2008 7:10 PM | Feedback (9)

Inversion of Control is NOT about testability

Jacob have an interesting perspective on testability: The thing is that using Typemock means that you can unit test literally any public method of any public class, regardless of any and all internal dependencies that class might have. And you can do so without changing the design and/or architecture of your software at all. In other words, using Typemock means that everything is testable. Unit testable. Seriously. Everything. .... Which is why I had such a hard time reading Jeffrey Palermo's latest blog post entitled “Inversion of Control is NOT about testability”. Since I know Jeffrey...

posted @ Saturday, August 16, 2008 6:41 PM | Feedback (3)

Putting the container to work: Refactoring NServiceBus configuration

One of the most common issues when people are building frameworks and applications that rely on a container is that they are not giving the container enough to do. Basically, they use the container to create some components, but they are doing a lot of things that the container could do for them outside of the container. Note: Code for this post can be in the Scratch Pad. NServiceBus and Mass Transit are good examples of that. I detailed some of the issues that I had with Mass Transit a while ago. Udi and...

posted @ Sunday, July 13, 2008 12:33 PM | Feedback (7)

Zero friction IoC: Auto registration is mandatory

This is the entire Binsor config file for a real application: import Castle.MonoRail.Framework import Castle.MonoRail.WindsorExtension import Rhino.Commons.Facilities from Rhino.Commons.ActiveRecord facility MonoRailFacility facility RhinoTransactionFacility facility ActiveRecordUnitOfWorkFacility: assembly = "HibernatingRhinos" for type in AllTypesBased of IController("HibernatingRhinos"): component type.Name, type for type in AllTypes("HibernatingRhinos").WhereNamespaceEq("HibernatingRhinos.Services"): component type.GetServiceInterface(), type And I am pretty confident that I am not going to have to do much in the future with those. And yes, you can do it with the fluent registration API as well.

posted @ Tuesday, May 13, 2008 4:08 PM | Feedback (6)

Binsor & Auto Registration - Making it even simpler

Here is the syntax that I am getting at... for type in AllTypesBased of IView("Rhino.Commons.Test"): component type for type in AllTypesWithAttribute of ControllerAttribute("Rhino.Commons.Test"): component type for type in AllTypes("Rhino.Commons.Test") \ .WhereNamespaceEq("Rhino.Commons.Test.Binsor"): component type for type in AllTypes("Rhino.Commons.NHibernate") \ .Where({ t as System.Type | t.Name.Contains("NHRepository") }): component "nh.repos", type.GetSeriveInterface(), type And this seems to cover just about any scenario that I can think of. Combine that with Binsor's extend facility, and we are more or less done.

posted @ Tuesday, May 13, 2008 8:21 AM | Feedback (3)

Adaptive Domain Models with Rhino Commons

Udi Dahan has been talking about this for a while now. As usual, he makes sense, but I am working in different enough context that it takes time to assimilate it. At any rate, we have been talking about this for a few days, and I finally sat down and decided that I really need to look at it with code. The result of that experiment is that I like this approach, but am still not 100% sold. The first idea is that we need to decouple the service layer from our domain implementation. But why? The...

posted @ Thursday, March 27, 2008 11:16 AM | Feedback (12)

DI & IoC are not about testing!

Dependency Injection & Inversion of Control Containers are not about testing! I hear this a lot recently. Dave Laribee mentioned that in the Hanselminutes podcast, The creators of Guise seems to think that this is the main concern (01:30 in the video). Oh, those techniques help, obviously. But it is not about unit testing. For me, it is like saying that the main purpose interfaces is to enable easier testing. DI & IoC are about decoupling, better flexibility, having a central place to go to and increasing the maintainability of out applications. Testing is important, but...

posted @ Wednesday, March 26, 2008 1:16 AM | Feedback (21)

Non Invasive API, take 2

A few days ago I presented my typical way of handling container driven polymorphism. // only use for selection public interface IRegion<T> : IRegion {} public void SetRegion(DependencyObject containerElement, string regionName) { IRegion region = (IRegion) IoC.TryResolve(typeof(IRegion<>).MakeGenericType(containerElement.GetType())); if (region != null) _regions.Add(regionName, region); } I got an email with some good questions, and it is worth a second post to clarify. The questions: The only thing I don’t like is that a lookup in the form of TryResolve(typeof(IRegion<>).MakeGenericType(containerElement.GetType())) would infer an explicit wrapper type for ever possible UI container type. On one hand it gives me the fine grain control I need...

posted @ Tuesday, March 25, 2008 12:58 AM | Feedback (4)

Non invasive API - Now with an IoC container

I talked about ways to avoid invasive API design, and a lot of people asked about how to handle this with a container. First, I want to make it clear that the previous example assumed that you can't rely on a container, so it used Poor Man IoC to do that. Now that we can assume that there is a container, this is another matter entirely. The API design now shifts to allow me to select the proper implementation from the container automatically. This generally ends up being either as a naming convention on top of a fixed interface, or...

posted @ Wednesday, March 19, 2008 11:37 PM | Feedback (14)

Evaluating IoC containers

Scott Hanselman is learning IoC, and he listed a lot of the IoC frameworks on the CLR. I was also pointed to this comparison IoC containers. I don't like that comparison, and I am not sure that I can quite explain it. Most of the time, comparison of IoC container focus on simple dependency resolving scenarios and the related configuration. From my point of view, it is like deciding to use C# or Java after reading a comparison of the syntax of an if statement. Dependency resolution is the most basic feature that an IoC container can have. Of...

posted @ Friday, March 14, 2008 12:11 PM | Feedback (5)

Interception as an extensibility mechanism

I got a request to allow system-mode for Rhino Security, something like this: using(Security.ActAsSystem()) { // in here the security behaves as if you have permission // to do everything // queries are not enhanced, etc. } It is not something that I really want to allow, so I started to think how we can implement this, I came up with the following solution: public class AuthorizationServiceWithActAsSystemSupport : IAuhorizationService { IAuhorizationService inner; public AuthorizationServiceWithActAsSystemSupport(IAuhorizationService inner) { this.inner = innner; } private bool IsActAsSystem { get { return true.Equals(Local.Data["act.as.system"]); } } public bool IsAllowed(IUser user, string operationName) { if(IsActAsSystem) return true; return inner.IsAllowed(user, operationName); } public void AddPermissionsToQuery(IUser user, string operationName, ICriteria query) { if(IsActAsSystem) return; inner.AddPermissionsToQuery(user, operationName, query); } // .. the rest } Now, all we need to do is...

posted @ Thursday, January 24, 2008 10:31 AM | Feedback (4)

AOP: Be aware where your point cuts are

So, this issue cause some head scratching today. We are using WIndsor's Automatic Transaction Management with NHibernate's flush-on-commit option, so if a transaction doesn't commit, nothing is written to the database. Anyway, this is a story about refactoring, and what it showed us. We performed the following refactoring: Some things that is important to understand, the LoginController is decorated with [Transactional], and there is a [Transaction] attribute on CreateUserLoggedInAuditRecord. When it was on the controller, it just worked. When we moved it to its own class, it didn't work. To be rather more exact, it worked, it just...

posted @ Wednesday, December 19, 2007 9:00 PM | Feedback (13)

DSL & IoC - Combining powerful concepts

I was just writing this line of code: DslExecuter<SchedulingDslEngine>.Create(“validateWebSiteIsUp”) When it occurred to me that this looks a look like an IoC resolve call. Which got me thinking about combining both concepts together, which gave me the shakes. The idea is that we can expose those dependencies like this: customers as ICustomerRepository fraudService as IFraudService alerts as IAlertService for customer in customers.FindAll(With.Orders): for order in customer.Orders: if fraudService.IsFraud(order): alerts.ForFaurdOn(order) if customer.Important: alerts.NotifyCustomerAboutFraud(customer) Leaving aside the mountain slope code*, consider what is going on here. We are exposing dependencies by specifying the types that we need. We can then get them through the IoC and execute the code in hand. This means that the...

posted @ Thursday, December 13, 2007 9:42 AM | Feedback (7)

Dogmatic? Who, me?

Jacob Proffitt calls me up to task for being inconsistent: In this, Ole Friis is echoing the response I got from the intimidating Oren Eini when I suggested that TypeMock makes arguments that couple DI with unit testing go away. The main weakness of Type Mock is its power, it allow me to take shortcuts that I don’t want to take, I want to get a system with low coupling and high cohesion. The implication is that he wouldn’t be developer enough to create a system with low coupling and high cohesion if he used powerful tools like...

posted @ Tuesday, December 11, 2007 9:54 PM | Feedback (3)

Inverting Inversion of Control

What do you think about this code? IoC.Container.Kernel.AddComponentInstance<IFoo>(this); IBar context = IoC.Resolve<IBar>();//needs IFoo For some reason it looks really funny to me. More seriously, this is a good way to involve components that you cannot control in the container.

posted @ Monday, December 10, 2007 1:36 AM | Feedback (4)

Envrionment Validation and Windsor Extensibility

So I was in Jermey Miller's talk about maintainable software echo system, and one of the thing that he mentioned that StructureMap does really well is the ability to ask the container to perform envrionment validations, to make sure that the envrionment is ready for us. I really liked the idea, so I pulled up the laptop and started spiking how to handle this issue. First, let us see Jeremy's solution: public class FileTextReader : ITextReader { [ValidateConfiguration] public void ValidateFileExistance() { if (File.Exists(fileName) == false) throw new FileNotFoundException("Could not find file " + fileName); } } So, when you ask structure map to validate the environment, it will...

posted @ Thursday, November 29, 2007 2:30 PM | Feedback (4)

Binsor 2.0

All credit should go to Craig Neuwirt, for some amazing feats of syntax. He has managed to extend Binsor to include practically all of Windsor's configuration schema. This is important because previously we had to resort to either manual / ugly stuff or go back to XML (see: manual & ugly). This is important because some of the more interesting things that you can do with Windsor are done using the facilities, and Craig has made sure that Binsor will support the main ones in a natural manner, including out of the box support for the standard configuration model. Let...

posted @ Thursday, October 25, 2007 1:54 AM | Feedback (13)

Analyzing a DSL implementation

You were just handed a strange DSL implementation, it does stuff, and it may be cool, but you have no idea how it works. Craig Neuwirt recently did a major overhaul of Windsor ( I am going to post soon with the details of how cool it is now ), but I am now faced with the question, how do you grok such a thing? I thought that it would be useful to put a list of what I am doing to understand how the internals now works. It goes without saying, but the nitpickers will ask, that a...

posted @ Thursday, October 25, 2007 1:19 AM | Feedback (1)

The IoC mind set: Validation

I think that I mentioned that I believe that having a good IoC container at your disposable can make you really shift the way you are structuring your code and architects solutions. Let us take for instance Validation as an example. The two examples that jump to mind are Castle.Components.Validation and the Validation Application Block. They both have the same general approach, you put an attribute on a property, and then you use another class to validate that the object meet its validation spec. This approach work, and it is really nice approach, for very simple input validation. Required fields,...

posted @ Sunday, October 21, 2007 8:28 PM | Feedback (15)

Dependency Injection doesn't cut it anymore

So, I showed how you can write an IoC container in 15 lines of code, obviously this means that containers such as Windsor, at ~52,000 lines of code are tremendously bloated and not worth using, right? Well, no. And the reason is that DI is now just one of the core functions of a container, it is the other things that it does that make it so useful. Since the discussion started from why you don't need IoC in Ruby, I decided to also explore the ideas in the Ruby frameworks. It seems like a typical Ruby IoC code is...

posted @ Saturday, October 20, 2007 9:40 PM | Feedback (11)

Building an IoC container in 15 lines of code

I am writing this post as a result of a discussion in the ALT.Net mailing list and DI containers in Ruby. Since I promised that I would build such a thing, it made it interesting to see how far I can minimize an IoC container. The result is, as I said, 15 lines of significant code (ignoring blank lines or line with just curly braces). You can see the sample model on the right. It is fairly typical model, I believe. I want to get the login controller instance without having to worry about the dependencies, and I want...

posted @ Saturday, October 20, 2007 8:39 PM | Feedback (3)

Teaching Reflection

I am going to teach Reflection to my students tomorrow. Instead of going by the book, I think that we will implement an IoC container. Nothing like going into the nuts & bolts of it in order to make people understand how stuff works. They are Morts, so this ties in very well into the discussion that I had on the weekend, about Mort's abilities. I'll report on Friday...

posted @ Wednesday, October 17, 2007 10:15 AM | Feedback (10)

And now THAT is flattering

Take a look at this Object Builder Bug, and David Hayden coverage of that bug. Extremely flattering, and a real credit to Hammett. When the criteria is: "It ain't Windsor", it says quite a bit. :-)

posted @ Saturday, October 06, 2007 12:46 AM | Feedback (1)

Convention over configuration: Structured approach

Hammett has a post that made me think. He is talking about configuring Spring for Java and has this to comment: I can’t understand this uncontrolled passion that java programmers carry for xml. I can certainly agree with him about that, but I got to the same point a long time ago with Windsor. I had an application which was rife with components. I am talking about many dozens of generic (as in MyComponent<T>) components, all of which required registration in the config file, which got to be fairly annoying very fast. I solved that by creating Binsor, a...

posted @ Thursday, September 20, 2007 10:51 PM | Feedback (1)

Dependency Injection in a Dynamic Environment

Scott Bellware joins the DI discussion from a completely different angel, the dynamic language point of view: The level of abstraction that we work at in .NET is appropriate to explicit inversion of control and thus dependency injection.  To make type mocking your main method of achieving testability in .NET development will drive your designs increasingly sap the maintainability of your code.  Maintainability and agility in a static environment are mostly the effect of applying appropriate static design patterns for static development.  [...snip...] The difference in my comfort level in doing this has a lot to do with the fact...

posted @ Thursday, August 23, 2007 12:52 AM | Feedback (5)

Dependency Injection: Separating the Container

In a previous post, I made the statement that I believe that using an IoC container should be transparent to the application code, and that a good IoC can and should be invisible to anything but the Main() method. I would like to expand a bit on this topic, cover the sample problem that Tobias had brought up: I never could achieve this and I'm wondering, what you mean by this statement. There a are always a lot of references to the DI/IoC container throughout the application. E.g. each IView that needs to be created to show a WinForm...

posted @ Thursday, August 23, 2007 12:11 AM | Feedback (5)

Complex problems in a dynamic environment

My last post made me think about how it is best to approach a problem in a dynamic environment. The problem that I have in mind is the one I solved with IoC and static typing here. The problem is as follows: You have several customers, each of them has its own database, with its own schema, data and behaviors, There is a common ground between the customers, but each does (different things!) differently. You need to handle each incoming user according to its associated customer. For the purpose of discussion, let us say that we want to list...

posted @ Tuesday, August 21, 2007 10:30 AM | Feedback (1)

Dependency Injection in Web Forms MVC

David Hayden has a post about the issue that you face when you are trying to use dependency injection in Web Forms MVC. I talked about similar issues here. He points out that this type of code is bad: protected Page_PreInit(object sender, EventArgs e) { // Constructor Injection of Data Access Service and View ICustomerDAO dao = Container.Resolve<ICustomerDAO>(): _presenter = new AddCustomerPresenter(dao,...

posted @ Thursday, June 28, 2007 1:40 AM | Feedback (6)

Challenge: Windsor Null Object Dependency Facility

In Scott Bellware's post about dependency injection, he has a comment about optional dependencies: Setter dependencies are optional.  Their types should have a Null Object pattern implementation, and if not it's often a good idea to decorate them with one.  For example, if an optional dependency hasn't been set, it might not be desirable to have a null reference exception when a method is invoked on it The challenge is to provide a facility for Windsor that will detect an optional dependency and fill it with a Null Object (i.e, an implementation that doesn't do anything). It is safe...

posted @ Thursday, June 28, 2007 12:58 AM | Feedback (8)

Hierarchical Containers

This is somewhat of a specific scenario, but let us assume that you have an application where you want to specialize the services of the applications by the current user. If the user belongs to the Northwind customer, you want to have one behavior, and if it belongs to the Southsand customer, you want to have a different behavior. All users from all others customers get the default behavior. To make it simple, let us talk about NHibernate configuration. You have a default schema that you use for most customers, and you specialize that for those customers that wants extra....

posted @ Thursday, June 21, 2007 2:31 AM | Feedback (2)

Using NHibernate Session Per Request with WCF Windsor Integration

Okay, this is a quickie, but here is how you can do it, you need to register a UnitOfWorkEndPointBehavior implementation on the container, and make sure that your WCF services are used through the WindsorServiceHost. That is all. What is the UnitOfWorkEndPointBehavior, you ask, here it is:public class UnitOfworkEndPointBehavior : IEndpointBehavior { public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) { foreach (DispatchOperation operation in endpointDispatcher.DispatchRuntime.Operations) { operation.CallContextInitializers.Add(new UnitOfWorkCallContextInitializer()); } } } public class UnitOfWorkCallContextInitializer : ICallContextInitializer { public object BeforeInvoke(InstanceContext instanceContext, IClientChannel channel, Message message) { ISession session = factory.OpenSession(); OperationContext.Items["NHibernate_Session"] = session; return session; } public void AfterInvoke(object correlationState) { ((IDisposable)correlationState).Dispose(); } } public static class UnitOfWork { public static ISession Current { get { return (ISession )OperationContext.Items["NHibernate_Session"]; } }

posted @ Thursday, June 14, 2007 7:35 AM | Feedback (15)

WCF Windsor Integration

Last night I commited WCF Integration to the Castle trunk. This is based in part on the work described here by Orand. The main idea here is that WCF should get the service instances from Windsor, which gives us all the usual advantages of IoC plus Windsor's interceptors capabilities. It isn't a lot of code, but it makes it much easier to work with WCF services. Using it on a web application: Call this in the beginning of the application (Global.Application_Start): WindsorServiceHostFactory.RegisterContainer(container); Create a MyService.svc file and put this in it:<%@ ServiceHost Service="component name in windsor" Factory="Castle.Facilities.WcfIntegration.WindsorServiceHostFactory, Castle.Facilities.WcfIntegration" %> Have...

posted @ Tuesday, June 12, 2007 8:09 AM | Feedback (7)

Windsor, Decorators and Chains of Responsabilityes, Oh YEAH!

A few days ago I made a small change to Windsor, the change was basically stopping Windsor from trying to resolve a dependency using a dependency that it is already resolving. Now, this is prettry hard to explain without a good example, so consider this one: Let us say that we have the standard Chain Of Responsability here, each finder will check its store for an item that matches the specification, and would call the next one in the chain if it can't. Now, previously you had to instruct Windsor explicitly about who was the next in the...

posted @ Monday, June 11, 2007 9:52 AM | Feedback (14)

Binsor: Native Facilities Support

Okay, I intended to post about this in more details, but I want to wrap up this day, I added support for native facilities in Binsor. By native I mean facilities that expect to be configured by Windsor XML configuration. Since I am mostly the only one that is writing Binsor based facilities, this has been a problem when people wanted to use the standard facilities. You can see the syntax here, very Yaml like, I think :-) I am going to post soon about how I managed to get this syntax to work.Facility("loggerFacility", LoggingFacility, loggingApi: "Log4net", configFile:...

posted @ Monday, June 11, 2007 1:18 AM | Feedback (3)

The Auto Mocking Container

Several months ago the guys from Eleutian released the Auto Mocking Container, a combination of Rhino Mocks and Windsor container. I looked at it at the time, and I liked it, but I didn't really get a chance to work with it until recently. You can see how a non trivial controller may look like on the left. It has a fair number of collaborators, for data access, logging, notifications, etc. This approach make building the controller very easy: public void DisplayOrdersForApproval() { if (AuthorizationService.AllowedToApproveOrders() == false) AccessForbidden(); PropertyBag["orders"] = Orders.FindAll( Where.Order.Status == OrderStatus.WaitingForApproval && Where.Order.Department == CurrentUser.Department ); } public void RejectOrder(Order order) { NotificationService.OrderRejected(order); Logger.Info("User {0} had rejected order {1}.", CurrentUser.Name,...

posted @ Friday, June 08, 2007 4:52 PM | Feedback (4)

Setting up Windsor for auto registration of components

I was asked how to do this, but this is frightfully simple: controllersAsm = Assembly.Load("MyApp.Controlls") for type in controllersAsm.GetTypes(): if typeof(BaseController).IsAssignableFrom(type): Component(type.Name, type) This example is using Binsor, executable configuration can do some really nice things. Another option would be to build a facility to do this, which is about the same amount of code.

posted @ Friday, June 08, 2007 10:59 AM | Feedback (6)

Rhino Commons, Repository<T> and Unit Of Work

Rhino Commons is a great collection of stuff that I gathered along the way, but never documented. There is a sample application (https://rhino-tools.svn.sourceforge.net/svnroot/rhino-tools/trunk/SampleApplications/Exesto), but not much more.  I want to spend a few minutes talking about the way the data access part of it works. This is post about how it works, not how to make it work (in other words, very little code here). Before I start, I want to mentions that Rhino Commons is (highly) opinionated software, unlike Castle or NHibernate. It is a separate place where I take what Castle & NHibernate gives me, add a mix...

posted @ Friday, June 08, 2007 1:59 AM | Feedback (14)

When IoC becomes transparent

My current project has a huge dependency on Windsor. Basically everything that goes on has to go through Windsor. This has made my life a lot simpler, but I just today noticed something interesting. Sometimes at the beginning of the application, we have defined the core services (logging, authorization authentication, etc) and then we forgot about them. What do I mean by that? Well, I mean that after the initial setup, we have continued to develop the application, but because of the way Windsor is structured, and because I have some defaults in the application (auto-configure controllers, for instance), it...

posted @ Friday, June 08, 2007 1:24 AM | Feedback (11)

Windsor Patterns

I have no idea how I missed it so far, but Alex has a set of posts showing all sorts of interesting usage patterns (and design patterns) that can be used with Windsor. Part 1 - Simple Configuration Part 2 - More Configuration (Arrays) Part 3 - Still More Configuration (Dictionaries) ...

posted @ Thursday, May 03, 2007 12:46 AM | Feedback (8)

Recommended approaches to AOP with Windsor

In my Policy Injection With Windsor (in 40 minutes), I mentioned that things like the Policy Injection Block are not a really good approach to doing AOP using Windsor. What I meant that I wouldn't build something like the Policy Application Block, simply because it doesn't really gives me anything special. The use cases for simple interception AOP are quite limited. Mostly logging, performance monitor, and that about it. But its very nature, AOP is an infrastructure entity, and will generally not take part of any meaningful business logic. Can someone think about an interesting...

posted @ Tuesday, March 13, 2007 11:05 PM | Feedback (0)

Building the Policy Injection in 40 Minutes with Windsor

David Hayden posted about the policy injection block, and he mentioned that he believe that it should be integrated into the various EntLib offerring. Since he is using Windsor already, I asked why he is not using Windsor's capabilities to do this. Apperantly, they are not well publicized, since he wasn't aware of it. Therefor, I decided to take a look at what it would take to implement the Policy Injection capabilities with Windsor. It took me about 40 minutes and 400 lines of code. I didn't look at the Policy Injection...

posted @ Wednesday, March 07, 2007 12:07 AM | Feedback (6)

Object Builder Get Bijection Support?

I just read this, and it looks extremely similar to the way Igloo is doing Bijection. Naturally I like the Igloo approach better, but it is interesting to see similar approaches appear independently.  

posted @ Sunday, February 25, 2007 1:46 AM | Feedback (0)

Mocking Injection

The guys from Eleutian had done it again, with a post that explains how you can use Windor and Rhino Mocks in order to make it easy to create the tests. Jacob is raising some concerns about this approach:Speed/peformance? Does making the container such an integral part of the test fixtures hurt performance? Setup has to be longer when we're creating the container the way we are. Does this matter? Only as long as the time saved when writing tests is larger than the time it takes to run them, which I'm sure is...

posted @ Friday, February 23, 2007 9:55 AM | Feedback (0)

Igloo: Model View Controller In ASP.Net

I wrote about Igloo before, but now I am writing after several weeks of using it for a big project of ours. A bit about the architecture, we are using MVC (by utilizing Windosr + Igloo) in a way that I find very elegant. The UI layer is composed of WebForms and Atlas, and the backend is Active Record using Repository<T>. Transactions are handled by the Automatic Transaction Management facility from Windsor. Let us think about creating a new policy, there are a lot of fields to fill, so the...

posted @ Wednesday, February 21, 2007 8:28 PM | Feedback (10)

Structure Map Fluent Interface

Now, I am not a user of StructureMap, but the interface looks cool:// Add an instance with properties registry.AddInstanceOf<IWidget>()   .WithName("DarkGreen")   .UsingConcreteType<ColorWidget>()   .WithProperty("Color").EqualTo("DarkGreen"); Jeremy calls it a DSL, but I don't think that it is the correct term, it is just using a diffeerent (and better) approach for coniguring it with code. The main problem I have with this is that it is something that breaks down when you need the complex stuff, because you...

posted @ Tuesday, February 20, 2007 9:55 PM | Feedback (0)

Battle Plans

The last time that I saw something like this, it was over an operational map and I had to capture a hill. Will you believe that the end result is even more complex?

posted @ Sunday, January 21, 2007 7:59 PM | Feedback (4)

My MSDN Article

My MSDN article has been published and can be found here. It covers using IoC (specifically Windsor) to create very flexible systems. Users of Rhino Commons will be able to recognize a lot of the thinking that went into building Rhino Commons. Specifically, the foundations of IRepositorty<T>. The article has been brewing for four or five months. It started as a blog post after a particulary annoying day, but it took a long time to create it properly, and it got too big for even what I would consider a blog post :-). I am really...

posted @ Friday, November 10, 2006 6:24 PM | Feedback (12)

Unit testing with NHibernate / Active Record

One of the more difficult regions to test in an application is the data access layer. It is difficult to test for several reasons: It is usually complicated - fetching data effectively is not something trivial in many cases. It can be highly dependant on the platform you are using, and moving between platforms can be a PITA. It is usually hard to...

posted @ Saturday, October 14, 2006 11:47 PM | Feedback (5)

NHibernate Query Generator 1.5 Is Done! [Time With Magic]

I have been working (and blogging about it) for a while, and I think that I finally hit the right combination of keys to make it compile, so I am shipping it :-) If you fail to recall, it started as a simple way to generate criteria queries in strongly typed manner. The first version didn't do much, and was fairly simple. As soon as I started using it, I began to want more, much more. If I was working with an open compiler (Boo), I could have written this as an extentions and...

posted @ Saturday, October 14, 2006 7:18 PM | Feedback (14)

Fighting the Evil XML, Take 2

David Haydem posts about using Windsor, I thought that I would take a shot at duplicating his configuration using Binsor.  You can check his post for the XML configuration, but that was 25 lines of code. The Binsor code is 6 lines :-) import BlogDataServices import DatabaseServices ...

posted @ Saturday, October 14, 2006 1:24 PM | Feedback (0)

More On Binsor: Natrual Component References

Well, I just added the last piece in what I consider the major features to Binsor, which is component references. I'm a big fan of decorators and chains of responsabilities, which mean that I tend to create a lot of references between objects. In Binsor, it is as natural as this: import Rhino.Commons ...

posted @ Saturday, September 16, 2006 6:07 AM | Feedback (2)

Minimal Configuration for Rhino Common Repository

This is the bare minimum that you need to do in order to use the repositories: <?xml version="1.0" encoding="utf-8" ?> <configuration>       <components> ...

posted @ Thursday, August 10, 2006 12:41 AM | Feedback (3)

IoC and fluent interfaces

You may have noticed that I like to play word games with code, so here is the Inversion of Control interface in Rhino Commons: The main goal is to be able to say:ISender sender = (ISender)IoC.Container.Resolve("email"); The Initialize() method is called at application start, and will set everything up for the rest of the application. This class is to fetch the repositories, so I can generate a complex object graph and handle some interesting scenarios from the start, using generic decorators. In the end, I didn't...

posted @ Sunday, July 30, 2006 5:05 PM | Feedback (5)

Complex Object Graphes

Recently I have been working on an application that require high level of configurability. I choose to use Castle's Windsor and Inversion of Control as the main principals when designing the application. I think I took a slightly different route than the normal one. I use Windsor to generate the entire object graph once, and then I start working with it. Actually, it is a little more complicated than that. The object graph just need a push (a call to Start() ) and it start working on its own, with no additional input/output from...

posted @ Tuesday, July 18, 2006 12:16 AM | Feedback (3)

Mock Objects And Mock Turtles

I just dicovered this web cast talking about TDD, Mocking, Dependency Injections, Design Patterns, etc. I am currently watching this, and it looks very good.

posted @ Monday, June 12, 2006 10:00 PM | Feedback (0)

Model View Controller In ASP.Net

As it turned out, it takes 20 lines of code to add MVC to ASP.Net*: public class ModelViewControllerHandlerFactory : IHttpHandlerFactory {     public IHttpHandler GetHandler(HttpContext context, ...

posted @ Saturday, May 20, 2006 10:50 AM | Feedback (2)