I Use This!
Moderate Activity


Analyzed about 15 hours ago. based on code collected about 19 hours ago.
Posted over 4 years ago
I’ve had a few requests over the last year and a bit for Visual Studio 2012 and 2013 support for Castle Visual Studio Integration. I released a preview with support for Visual Studio 2012 nearly two years ago, but last weekend bit the bullet after ... [More] a little push from a long time user. You can download the source code from GitHub if you are interested and you can get the binaries (a VSIX) from the CVSI page. The 2012 and 2013 releases are not available through the Visual Studio Extension Manager, see the CVSI page if you want to know why. [Less]
Posted over 4 years ago by Krzysztof
A while ago (almost 4 years ago, to be precise) Ben Hall wrote a blogpost about using Castle DictionaryAdapter to build a simple, strongly typed wrapper aroud application settings. While extremely simple, and gets the job done, there are a few ways ... [More] it can be improved. With that, this blogpost can be treated as an introduction to Castle DictionaryAdapter (which sadly has precisely zero documentation). While the apprpach is really simple, we're going to take a detailed look and take it slowly, which is why this post is fairly long. Buckle up. What is DictionaryAdapter In a nutshell DictionaryAdapter is a simple tool to provide strongly typed wrappers around IDictionary<string , object> Here's a simple example: // we have a dictionary... var dictionary = new Dictionary<string, object> { { "Name", "Stefan" }, { "Age", 30 } }; // ...and an adapter factory factory = new DictionaryAdapterFactory(); // we build the adapter for the dictionary var adapter = factory.GetAdapter<IPerson>(dictionary); Debug.Assert(adapter.Name == "Stefan"); Wrapping app settings While the project is called DictionaryAdapter in fact it can do a bit more than just wrap dictionaries (as in IDictionary). It can be used to wrap XmlNodes or NameValueCollections like Configuration.AppSettings and this last scenario, is what we're going to concentrate on. The goals We've got a few goals in mind for that project: strongly typed — we don't want our settings to be all just strings grouped — settings that go together, should come together (think username and password should be part of a single object) partitioned — settings that are separate should be separate (think SQL database connection string and Azure service bus url) fail fast — when a required setting is missing we want to know ASAP, not much later, deep in the codebase when we first try to use it simple to use — we want the junior developer who joins the team next week to be able to use it properly. With that in mind, let's get to it. Getting started DictionaryAdapter lives in Castle.Core (just like DynamicProxy), so to get started we need to get the package from Nuget: Install-Package Castle.Core Once this is done and you're not using Resharper make sure to add using Castle.Components.DictionaryAdapter; to make the right types available. The config file Here's our config file, we'll be dealing with. Notice it follows a simple naming convention with prefixes to make it easy to group common settings together. This is based on a real project. <?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings> <add key="environment-type" value="Local" /> <add key="environment-log-minimum-level" value="Debug" /> <add key="auth0-client-id" value="abc123abc" /> <add key="auth0-client-secret" value="123abc123abc" /> <add key="auth0-domain" value="abc123.auth0.com" /> <add key="auth0-database-connection-name" value="ABC123" /> <add key="auth0-token-expiration-seconds" value="3600" /> </appSettings> </configuration> As you can see we have two sets of settings here. One for general environment configuration, and another one for integration with Auth0. Config interfaces Now let's proceed to creating our interfaces, exposing the configuration values to our application. We follow a naming convention where the name of config value corresponds to type/property on the interface. This makes it trivial to see which config value maps to which property on which interface. For clarity I'd also recommend putting the interfaces in a designated namespace, like MyApp.Configuration. public interface IEnvironment { EnvironmentType Type { get; } LogEventLevel LogMinimumLevel { get; } } public interface IAuth0 { string ClientId { get; } string ClientSecret { get; } string Domain { get; } string DatabaseConnectionName { get; } int TokenExpirationSeconds { get; } } Having the interfaces and the config we can start writing the code to put the two together Bare minimum Let's rewrite the code from the beginning of the post to use our config file and interfaces. If you're not using Resharper you'll have to manually add a reference to System.Configuration.dll for the following to work. var factory = new DictionaryAdapterFactory(); var environment = factory.GetAdapter<IEnvironment>(ConfigurationManager.AppSettings); Debug.Assert(environment.Type == EnvironmentType.Local); If we run it now, we'll get a failure. DictionaryAdapter doesn't know about our naming convention, so we have to teach it how to map the type/property to a config value. Implementing DictionaryBehaviorAttribute There are two ways to customise how DictionaryAdapter operates. Transparent, using an overload to GetAdapter and passing a PropertyDescriptor with customisations there. Declarative, using attributes on the adapter interfaces to specify the desired behaviour. If you've used Action Filters in ASP.NET MVC, it will feel familiar. In this example we're going to use the latter. To begin, we need to create a new attribute, inheriting from DictionaryBehaviorAttribute, and apply it to our two interfaces public class AppSettingWrapperAttribute : DictionaryBehaviorAttribute, IDictionaryKeyBuilder { private readonly Regex converter = new Regex("([A-Z])", RegexOptions.Compiled); public string GetKey(IDictionaryAdapter dictionaryAdapter, string key, PropertyDescriptor property) { var name = dictionaryAdapter.Meta.Type.Name.Remove(0, 1) + key; var adjustedKey = converter.Replace(name, "-$1").Trim('-'); return adjustedKey; } } We create the attribute and implement IDictionaryKeyBuilder interface, which tells DictionaryAdapter we want to have a say at mapping the property to a proper key in the dictionary. Using a trivial regular expression we map NameLikeThis to Name-Like-This. Having done that, if we run the application again, the assertion will pass. Fail Fast If we remove the environment-log-minimum-level setting from the config file, and run the app again, it will still pass just fine. In fact, since LogEventLevel (which comes from Serilog logging framework) in an enum, therefore a value type, if we read the property everything will seem to have worked just fine. A default value for the enum will be returned. This is not the behaviour that we want. We want to fail fast, that is if the value is not present or not valid, we want to know. To do it, we need two modifications to our AppSettingWrapperAttribute Eager fetching First we want the adapter to eagerly fetch values for every property on the interface. That way if something is wrong, we'll know, even before we try to access the property in our code. To do that, we implement one more interface — IPropertyDescriptorInitializer. It comes with a single method, which we implement as follows: public void Initialize(PropertyDescriptor propertyDescriptor, object[] behaviors) { propertyDescriptor.Fetch = true; } Validating missing properties To ensure that each setting has a value, we need to insert some code into the process of reading the values from the dictionary. To do that, there is another interface we need to implement: IDictionaryPropertyGetter. This will allow us to inspect the value that has been read, and throw a helpful exception if there is no value. public object GetPropertyValue(IDictionaryAdapter dictionaryAdapter, string key, object storedValue, PropertyDescriptor property, bool ifExists) { if (storedValue != null) return storedValue; throw new InvalidOperationException(string.Format("App setting \"{0}\" not found!", key.ToLowerInvariant())); } If we run the app now, we'll see that it fails, as we expect, telling us that we forgot to set environment-log-minimum-level in our config file. Wrapping up That's it. Single attribute and a minimal amount of bootstrap code is all that's needed to get nice, simple to use wrappers around application settings. Additional bonus is, that this is trivial to integrate with your favourite IoC container. All code is available in this gist. [Less]
Posted almost 5 years ago by nore...@blogger.com (Mike Hadlow)
I’ve been a long time fan of IoC (or DI) containers ever since I first discovered Castle Windsor back in 2007. I’ve used Windsor in every major project I’ve been involved in since then, and if you’d gone to a developer event in the late naughties ... [More] , you may well have encountered me speaking about Windsor. Indeed, Seb Lambla had the cheek to call me ‘Windsor man’. I shall label him ‘Rest-a-man’ in revenge. When I started working on EasyNetQ in 2011, I initially thought it would be a very simple lightweight wrapper around the RabbitMQ.Client library. The initial versions were very procedural, ‘just get it done’, script-ish code burps. But as it turned into a more serious library, I started to factor the different pieces into more SRPish classes using dependency injection. At this point I was doing poor-man’s dependency injection, with an initial piece of wire-up code in the RabbitHutch class. As EasyNetQ started to gain some traction outside 15below, I began to get questions like, “how do I use a different serializer?” And “I don’t like your error handling strategy, how can I implement my own?” I was also starting to get quite bored of maintaining the ever-growing wire up code. The obvious solution was to introduce a DI container, but I was very reluctant to take a dependency on something like Windsor. Writing a library is a very different proposition than writing an application. Every dependency you introduce is a dependency that your user also has to take. Imagine you are a happily using AutoFac and suddenly Castle.Windsor appears in your code base, or even worse, you are an up-to-date Windsor user, but EasyNetQ insists on installing an old version of Windsor alongside. Nasty. Windsor is an amazing library, some of its capabilities are quite magical, but I didn’t need any of these advanced features in EasyNetQ. In fact I could be highly constrained in my DI container requirements: I only needed singleton instances. The lifetime of all DI provided components matches the lifetime of the main IBus interface. I didn’t need the container to manage component disposal. I didn’t need open generic type registration. I was happy to explicitly register all my components, so I didn’t need convention based registration. I only needed constructor injection. I can guarantee that a component implementation will only have a single constructor. With this highly simplified list of requirements, I realised that I could write a very simple DI container in just few lines of code (currently 113 as it turns out). My super simple container only provides two registration methods. The first takes a service interface type and a instance creation function: IServiceRegister Register<TService>(Func<IServiceProvider, TService> serviceCreator) where TService : class; The second takes an instance type and an implementation type: IServiceRegister Register<TService, TImplementation>() where TService : class where TImplementation : class, TService; These are both defined in a IServiceRegister interface. There is also a single Resolve method in an IServiceProvider interface: TService Resolve<TService>() where TService : class; You can see all 113 lines of the implementation in the DefaultServiceProvider class. As you can see, it’s not at all complicated, just three dictionaries, one holding the list of service factories, another holding a list of registrations, and the last a list of instances. Each registration simply adds a record to the instances dictionary. When Resolve is called, a bit of reflection looks up the implementation type’s constructor and invokes it, recursively calling resolve for each constructor argument. If the service is provided by a service factory, it is invoked instead of the constructor. I didn’t have any worries about performance. The registration and resolve code is only called once when a new instance of IBus is created. EasyNetQ is designed to be instantiated at application start-up and for that instance to last the lifetime of the application. For 90% of applications, you should only need a single IBus instance. EasyNetQ’s component are registered in a ComponentRegistration class. This provides an opportunity for the user to register services ahead of the default registration, and since the first to register wins, it provides an easy path for users to replace default services implementations with their own. Here’s an example of replacing EasyNetQ’s default console logger with a custom logger: var logger = new MyLogger();var bus = RabbitHutch.CreateBus(connectionString, x => x.Register<IEasyNetQLogger>(_ => logger)); You can replace pretty much any of the internals of EasyNetQ in this way: the logger, the serializer, the error handling strategy, the dispatcher threading model … Check out the ComponentRegistration class to see the whole list. Of course the magic of DI containers, the first rule of their use, and the thing that some people find extraordinarily hard to grok, is that I only need one call to Resolve in the entire EasyNetQ code base at line 146 in the RabbitHutch class: return serviceProvider.Resolve<IBus>(); IoC/DI containers are often seen as very heavyweight beasts that only enterprise architecture astronauts could love, but nothing could be more wrong. A simple implementation only needs a few lines of code, but provides your application, or library, with considerable flexibility. EasyNetQ is open source under the (very flexible) MIT licence. Feel free to cut-n-paste my DefaultServiceProvider class for your own use. [Less]
Posted almost 5 years ago by Krzysztof
Every non-trivial .NET application ends up using configuration file for its settings. It's the standard mechanism that's fairly well adopted across the community. That doesn't mean however, that it's simple to deal with. There have been many various ... [More] approaches to dealing with the problem, including some from Microsoft. There are a few open source ones, including one from my colleague, Andrew. Yet another (not even original) approach This brings us to Castle DictionaryAdapter. Part of the Castle project that never got much traction, partially to poor (read non-existent) documentation. Somewhat similar to DynamicProxy, DictionaryAdapter concentrates on dynamically generating strongly typed wrappers around dictionaries or XML. The idea of using it for wrapping configuration values is not new. Ben blogged about it a few years ago, and I always liked the simplicity and readability of the approach, and how little effort it required. I started working on a project recently, that has a whole bunch of different sets of config values, which led me to adding some small improvements to the approach. Not just one big Config God Object One common mistake (regardless of the approach) is that all the unrelated settings end up in a single massive configuration God Object. There is nothing inherent about the DictionaryAdapter approach forcing you to go down that path. You can split your configuration logically across a few configuration interfaces public interface SmtpConfiguration { string Name { get; set; } int Port { get; set; } } public interface SomeOtherConfig { //stuff } // and in the config file: <appSettings> <name>value</name> <port>25</port> <!--  stuff --> </appSettings> Taking it a bit further, we might explicitly partition the values using prefixes: <appSettings> <smtp:name>value</smtp:name> <smtp:port>25</smtp:port> <stuff:something>bla</stuff:something> <!--  other stuff --> </appSettings> DictionaryAdapter knows how to properly resolve prefixed values using KeyPrefixAttribute. [KeyPrefix("smtp:")] public interface SmtpConfiguration { string Name { get; set; } int Port { get; set; } } Fail fast One other missing big, is shortening the feedback loop. We don't want to learn we have an invalid or missing value at some later point in the application's lifecycle when we try to read it for the first time. We want to know about it as soon as possible. Preferably, when the application starts up (and in a test). The first problem, we could solve with FetchAttribute Which forces a property to be read when the adapter is constructed, therefore forcing exception in cases where, for example, your property is of type TimeSpan but your config value is not a valid representation of time span. To solve the other problem we need a little bit of code. In fact, to simplify things, we can merge that with what KeyPrefixAttribute and FetchAttribute provide, to have all the functionality we need in a single type. public class AppSettingsAttribute : KeyPrefixAttribute, IDictionaryPropertyGetter, IPropertyDescriptorInitializer { public AppSettingsAttribute(string keyPrefix) : base(keyPrefix) { } public object GetPropertyValue(IDictionaryAdapter dictionaryAdapter, string key, object storedValue, PropertyDescriptor property, bool ifExists) { if (storedValue == null && IsRequired(ifExists)) { throw new ArgumentException("No valid value for '" + key + "' found"); } return storedValue; } public void Initialize(PropertyDescriptor propertyDescriptor, object[] behaviors) { propertyDescriptor.Fetch = true; } private static bool IsRequired(bool ifExists) { return ifExists == false; } } Now our configuration interface changes to: [AppSettings("smtp:")] public interface SmtpConfiguration { string Name { get; set; } int Port { get; set; } } Not only do we get a nice, readable, testable strongly typed access to our settings, that can easily be put in an IoC container. We also are going to get an early exception if we put an invalid value in the config, or we forget about doing it at all. The full code is on github. [Less]
Posted over 5 years ago by Krzysztof
In the previous post I said there's one more new feature in Windsor 3.2 related to open generic components. Take the following class for example: public class Foo<T, T2> : IFoo<T> { } Notice it has arity of 2 (two generic parameters, T ... [More] and T2) and the interface it implements has arity of 1. If we have a generic component for this class what should be supplied for T2 when we want to use it as IFoo<Bar>? By default, if we just register the component and then try to use it we'll be greeted with an exception like the following: Requested type GenericsAndWindsor.IFoo`1[GenericsAndWindsor.Bar] has 1 generic parameter(s), whereas component implementation type GenericsAndWindsor.Foo`2[T,T2] requires 2. This means that Windsor does not have enough information to properly create that component for you. You can instruct Windsor which types it should use to close this generic component by supplying an implementation of IGenericImplementationMatchingStrategy. Please consut the documentation for examples of how to do that. Specifying implementation generic arguments: IGenericImplementationMatchingStrategy The IGenericImplementationMatchingStrategy interface allows you to plug in your own logic telling Windsor how to close the implementation type for a given requested service. The following trivial implementation simply uses string for the other argument, therefore allowing the component to be successfully constructed. public class UseStringGenericStrategy : IGenericImplementationMatchingStrategy { public Type[] GetGenericArguments(ComponentModel model, CreationContext context) { return new[] { context.RequestedType.GetGenericArguments().Single(), typeof (string) }; } } The contract is quite simple, given a ComponentModel and CreationContext (which will tell you what the requested closed type is) you return the right types to use for generic arguments when closing the implementation type of the model. You hook it up in exactly the same way as IGenericServiceStrategy (and yes, there's an overload that allows you to specify both). container.Register(Component.For(typeof (IFoo<>)) .ImplementedBy(typeof (Foo<,>), new UseStringGenericStrategy()) .LifestyleTransient()); Now the service will resolve successfully. [Less]
Posted over 5 years ago by Krzysztof
While Windsor supported open generics components since pretty much forever, there's been some improvements in version 3.2 that I haven't blogged about yet, but which can be pretty useful in some advanced scenarios. I'll cover them in this and future ... [More] blogpost. Just so we're clear — what are open generic components? So what are open generic components? Components based on a generic type where we don't specify the generic arguments. Like the following: // register container.Register(Component.For(typeof (IFoo<>)) .ImplementedBy(typeof (Foo<>)) .LifestyleTransient()); // will provide IFoo<Bar>, IFoo<Baz>, IFoo<any_valid_type> In this case we say that the component provides IFoo<> closed over Bar, Baz etc Being picky about what we're closing over: IGenericServiceStrategy Sometimes we want to restrict the types we want our components to support. C# language allows us to use generic constraints to specify that, and Windsor will obviously respect that, but sometimes we need to go beyond what language provides. One realistic example might be restricting to specific types from a given assembly, like in this StackOverflow question. Windsor 3.2 has a new hook point for just that — IGenericServiceStrategy, which allows you to plug custom logic to specify whether you want a component to support a given closed version of it's open generic service. Here's a sample implementation limiting to types from a single assembly: public class OnlyFromAssemblyStrategy : IGenericServiceStrategy { private readonly Assembly assembly; public OnlyFromAssemblyStrategy(Assembly assembly) { this.assembly = assembly; } public bool Supports(Type service, ComponentModel component) { return service.GetGenericArguments().Single().Assembly == assembly; } } To hook the strategy: container.Register(Component.For(typeof (IFoo<>)) .ImplementedBy(typeof (Foo<>), new OnlyFromAssemblyStrategy(someAsembly)) .LifestyleTransient()); Now when you need IFoo<SomeTypeFromWrongAssembly> either another component will need to supply it, or the dependency will not be satisfied (which, if the dependency is not optional, will result in exception). [Less]
Posted over 5 years ago
I know, this is a weird requirement, but sometimes they appear in your backlog. The story is: as company XXX I want to expose a service based on WCF in IIS without having the .svc suffix in the address. I’m actually using Castle Windsor WCF Integration to resolve my service class with castle, and it [...]
Posted almost 6 years ago by Krzysztof
Windsor 3.2 release is now live on nuget and sourceforge. This release is mostly about bugfixes and incremental improvements and while some breaking changes were made, for vast majority of users this will be a drop-in update. The highlights of the ... [More] release are in the documentation, so I won't repeat them here. End of an era It is the last release to support .NET 3.5 and Silverlight. Also, I'm thinking of sunsetting (such a nice word) Remoting facility, Factory Support facility (the one that allows you to specify factory method via XML, not to be confused with Typed Factory facility), Event Wiring facility and Synchronize facility. Obviously, Windsor being a community driven project, if someone wants to step in and take over any of these facilities we'll keep updating them. Otherwise this will likely be their last release. [Less]
Posted about 6 years ago
This post describes a generalized convention for Castle Windsor that handles AppSettings primitives. In my previous post I explained how Convention over Configuration is the preferred way to use a DI Container. Some readers asked to see some ... [More] actual convention implementations (although I actually linked to them in the post). In fact, I've previously showcased some simple conventions expressed with Castle Windsor's API.. In this post I'm going to show you another convention, which is completely reusable. Feel free to copy and paste :) Most conventions are really easy to implement. Actually, sometimes it takes more effort to express the specification than it actually takes to implement it. This convention deals with Primitive Dependencies. In my original post on the topic I included an AppSettingsConvention class as part of the code listing, but that implementation was hard-coded to only deal with integers. This narrow convention can be generalized: The AppSettingsConvention should map AppSettings .config values into Primitive Dependencies. If a class has a dependency, the name of the dependency is assumed to be the name of the constructor argument (or property, for that matter). If, for example, the name of a constructor argument is top, this is the name of the dependency. If there's an appSettings key with the same name in the .config, and if there's a known conversion from string to the type of the dependency, the .config value is converted and used. Example requirement: int top Consider this constructor: public DbChartReader(int top, string chartConnectionString) In this case the convention should look after an AppSettings key named top as well as check whether there's a known conversion from string to int (there is). Imagine that the .config file contains this XML fragment: <appSettings>   <add key="top" value="40" /> </appSettings> The convention should read "40" from the .config file and convert it to an integer and inject 40 into a DbChartReader instance. Example requirement: Uri catalogTrackBaseUri Consider this constructor: public CatalogApiTrackLinkFactory(Uri catalogTrackBaseUri) In this case the convention should look after an AppSettings key named catalogTrackBaseUri and check if there's a known conversion from string to Uri. Imagine that the .config file contains this XML fragment: <appSettings>   <add key="catalogTrackBaseUri" value="http://www.ploeh.dk/foo/img/"/>   <add key="foo" value="bar"/>   <add key="baz" value="42"/> </appSettings> The convention should read "http://www.ploeh.dk/foo/img/" from the .config file and convert it to a Uri instance. Implementation By now it should be clear what the conventions should do. With Castle Windsor this is easily done by implementing an ISubDependencyResolver. Each method is a one-liner: public class AppSettingsConvention : ISubDependencyResolver {     public bool CanResolve(         CreationContext context,         ISubDependencyResolver contextHandlerResolver,         ComponentModel model,         DependencyModel dependency)     {         return ConfigurationManager.AppSettings.AllKeys                 .Contains(dependency.DependencyKey)             && TypeDescriptor                 .GetConverter(dependency.TargetType)                 .CanConvertFrom(typeof(string));     }       public object Resolve(         CreationContext context,         ISubDependencyResolver contextHandlerResolver,         ComponentModel model,         DependencyModel dependency)     {         return TypeDescriptor             .GetConverter(dependency.TargetType)             .ConvertFrom(                 ConfigurationManager.AppSettings[dependency.DependencyKey]);     } } The ISubDependencyResolver interface is an example of the Tester-Doer pattern. Only if the CanResolve method returns true is the Resolve method invoked. The CanResolve method performs two checks: Is there an AppSettings key in the configuration which is equal to the name of the dependency? Is there a known conversion from string to the type of the dependency? If both answers are true, then the CanResolve method returns true. The Resolve method simply reads the .config value and converts it to the appropriate type and returns it. Adding the convention to an IWindsorContainer instance is easy: container.Kernel.Resolver.AddSubResolver(     new AppSettingsConvention());            Summary The AppSettingsConvention is a completely reusable convention for Castle Windsor. With it, Primitive Dependencies are automatically wired the appropriate .config values if they are defined. This blog is totally free, but if you like it, please buy me a cup of coffee. [Less]
Posted about 6 years ago
This post explains why a DI Container is useful with Convention over Configuration while Poor Man's DI might be a better fit for a more explicit Composition Root. It seems to me that lately there's been a backlash against DI Containers among ... [More] alpha geeks. Many of the software leaders that I myself learn from seem to dismiss the entire concept of a DI Container, claiming that it's too complex, too 'magical', that it isn't a good architectural pattern, or that the derived value doesn't warrant the 'cost' (most, if not all, DI Containers are open source, so they are free in a monetary sense, but there's always a cost in learning curve etc.). This must have caused Krzysztof Koźmic to write a nice article about what sort of problem a DI Container solves. I agree with the article, but want to provide a different perspective here. In short, it makes sense to me to illustrate the tradeoffs of Poor Man's DI versus DI Containers in a diagram like this: The point of the diagram is that Poor Man's DI can be valuable because it's simple, while a DI Container can be either valuable or pointless depending on how it's used. However, when used in a sufficiently sophisticated way I consider a DI Container to offer the best value/cost ratio. When people criticize DI Containers as being pointless I suspect that what really happened was that they gave up before they were out of the Trough of Disillusionment. Had they continued to learn, they might have arrived at a new Plateau of Productivity. DI style Advantages Disadvantages Poor Man's DI Easy to learn Strongly typed High maintenance Explicit Register Weakly typed Convention over Configuration Low maintenance Hard to learn Weakly typed There are other, less important advantages and disadvantages of each approach, but here I'm focusing on three main axes that I consider important: How easy is it to understand and learn? How soon will you get feedback if something is not right? How easy is it to maintain? The major advantage of Poor Man's DI is that it's easy to learn. You don't have to learn the API of any DI Container (Unity, Autofac, Ninject, StructureMap, Castle Windsor, etc.) and while individual classes still use DI, once you find the Composition Root it'll be evident what's going on and how object graphs are constructed. No 'magic' is involved. The second big advantage of Poor Man's DI is often overlooked: it's strongly typed. This is an advantage because it provides the fastest feedback about correctness that you can get. However, strong typing cuts both ways because it also means that every time you refactor a constructor, you will break the Composition Root. If you are sharing a library (Domain Model, Utility, Data Access component, etc.) between more than one application (unit of deployment), you may have more than one Composition Root to maintain. How much of a burden this is depends on how often you refactor constructors, but I've seen projects where this happens several times each day (keep in mind that constructor are implementation details). If you use a DI Container, but explicitly Register each and every component using the container's API, you lose the rapid feedback from strong typing. On the other hand, the maintenance burden is also likely to drop because of Auto-wiring. Still, you'll need to register each new class or interface when you introduce them, and you (and your team) still has to learn the specific API of that container. In my opinion, you lose more advantages than you gain. Ultimately, if you can wield a DI Container in a sufficiently sophisticated way, you can use it to define a set of conventions. These conventions define a rule set that your code should adhere to, and as long as you stick to those rules, things just work. The container drops to the background, and you rarely need to touch it. Yes, this is hard to learn, and is still weakly typed, but if done right, it enables you to focus on code that adds value instead of infrastructure. An additional advantage is that it creates a positive feedback mechanism forcing a team to produce code that is consistent with the conventions. Example: Poor Man's DI The following example is part of my Booking sample application. It shows the state of the Ploeh.Samples.Booking.Daemon.Program class as it looks in the git tag total-complexity (git commit ID 64b7b670fff9560d8947dd133ae54779d867a451). var queueDirectory =     new DirectoryInfo(@"..\..\..\BookingWebUI\Queue").CreateIfAbsent(); var singleSourceOfTruthDirectory =     new DirectoryInfo(@"..\..\..\BookingWebUI\SSoT").CreateIfAbsent(); var viewStoreDirectory =     new DirectoryInfo(@"..\..\..\BookingWebUI\ViewStore").CreateIfAbsent();   var extension = "txt";   var fileDateStore = new FileDateStore(     singleSourceOfTruthDirectory,     extension);   var quickenings = new IQuickening[] {     new RequestReservationCommand.Quickening(),     new ReservationAcceptedEvent.Quickening(),     new ReservationRejectedEvent.Quickening(),     new CapacityReservedEvent.Quickening(),     new SoldOutEvent.Quickening() };   var disposable = new CompositeDisposable(); var messageDispatcher = new Subject<object>(); disposable.Add(     messageDispatcher.Subscribe(         new Dispatcher<RequestReservationCommand>(             new CapacityGate(                 new JsonCapacityRepository(                     fileDateStore,                     fileDateStore,                     quickenings),                 new JsonChannel<ReservationAcceptedEvent>(                     new FileQueueWriter<ReservationAcceptedEvent>(                         queueDirectory,                         extension)),                 new JsonChannel<ReservationRejectedEvent>(                     new FileQueueWriter<ReservationRejectedEvent>(                         queueDirectory,                         extension)),                 new JsonChannel<SoldOutEvent>(                     new FileQueueWriter<SoldOutEvent>(                         queueDirectory,                         extension)))))); disposable.Add(     messageDispatcher.Subscribe(         new Dispatcher<SoldOutEvent>(             new MonthViewUpdater(                 new FileMonthViewStore(                     viewStoreDirectory,                     extension)))));   var q = new QueueConsumer(     new FileQueue(         queueDirectory,         extension),     new JsonStreamObserver(         quickenings,         messageDispatcher));   RunUntilStopped(q); Yes, that's a lot of code. I deliberately chose a non-trivial example to highlight just how much stuff there might be. You don't have to read and understand all of this code to appreciate that it might require a bit of maintenance. It's a big object graph, with some shared subgraphs, and since it uses the new keyword to create all the objects, every time you change a constructor signature, you'll need to update this code, because it's not going to compile until you do. Still, there's no 'magical' tool (read: DI Container) involved, so it's pretty easy to understand what's going on here. As Dan North put it once I saw him endorse this technique: 'new' is the new 'new' :) Once you see how Explicit Register looks, you may appreciate why. Example: Explicit Register The following example performs exactly the same work as the previous example, but now in a state (git tag: controllers-by-convention; commit ID: 13fc576b729cdddd5ec53f1db907ec0a7d00836b) where it's being wired by Castle Windsor. The name of this class is DaemonWindsorInstaller, and all components are explictly registered. Hang on to something. container.Register(Component     .For<DirectoryInfo>()     .UsingFactoryMethod(() =>         new DirectoryInfo(@"..\..\..\BookingWebUI\Queue").CreateIfAbsent())     .Named("queueDirectory")); container.Register(Component     .For<DirectoryInfo>()     .UsingFactoryMethod(() =>         new DirectoryInfo(@"..\..\..\BookingWebUI\SSoT").CreateIfAbsent())     .Named("ssotDirectory")); container.Register(Component     .For<DirectoryInfo>()     .UsingFactoryMethod(() =>         new DirectoryInfo(@"..\..\..\BookingWebUI\ViewStore").CreateIfAbsent())     .Named("viewStoreDirectory"));              container.Register(Component     .For<IQueue>()     .ImplementedBy<FileQueue>()     .DependsOn(         Dependency.OnComponent("directory", "queueDirectory"),         Dependency.OnValue("extension", "txt")));   container.Register(Component     .For<IStoreWriter<DateTime>, IStoreReader<DateTime>>()     .ImplementedBy<FileDateStore>()     .DependsOn(         Dependency.OnComponent("directory", "ssotDirectory"),         Dependency.OnValue("extension", "txt"))); container.Register(Component     .For<IStoreWriter<ReservationAcceptedEvent>>()     .ImplementedBy<FileQueueWriter<ReservationAcceptedEvent>>()     .DependsOn(         Dependency.OnComponent("directory", "queueDirectory"),         Dependency.OnValue("extension", "txt"))); container.Register(Component     .For<IStoreWriter<ReservationRejectedEvent>>()     .ImplementedBy<FileQueueWriter<ReservationRejectedEvent>>()     .DependsOn(         Dependency.OnComponent("directory", "queueDirectory"),         Dependency.OnValue("extension", "txt"))); container.Register(Component     .For<IStoreWriter<SoldOutEvent>>()     .ImplementedBy<FileQueueWriter<SoldOutEvent>>()     .DependsOn(         Dependency.OnComponent("directory", "queueDirectory"),         Dependency.OnValue("extension", "txt")));   container.Register(Component     .For<IChannel<ReservationAcceptedEvent>>()     .ImplementedBy<JsonChannel<ReservationAcceptedEvent>>()); container.Register(Component     .For<IChannel<ReservationRejectedEvent>>()     .ImplementedBy<JsonChannel<ReservationRejectedEvent>>()); container.Register(Component     .For<IChannel<SoldOutEvent>>()     .ImplementedBy<JsonChannel<SoldOutEvent>>());   container.Register(Component     .For<ICapacityRepository>()     .ImplementedBy<JsonCapacityRepository>());   container.Register(Component     .For<IConsumer<RequestReservationCommand>>()     .ImplementedBy<CapacityGate>()); container.Register(Component     .For<IConsumer<SoldOutEvent>>()     .ImplementedBy<MonthViewUpdater>());   container.Register(Component     .For<Dispatcher<RequestReservationCommand>>()); container.Register(Component     .For<Dispatcher<SoldOutEvent>>());   container.Register(Component     .For<IObserver<Stream>>()     .ImplementedBy<JsonStreamObserver>()); container.Register(Component     .For<IObserver<DateTime>>()     .ImplementedBy<FileMonthViewStore>()     .DependsOn(         Dependency.OnComponent("directory", "viewStoreDirectory"),         Dependency.OnValue("extension", "txt"))); container.Register(Component     .For<IObserver<object>>()     .UsingFactoryMethod(k =>     {         var messageDispatcher = new Subject<object>();         messageDispatcher.Subscribe(k.Resolve<Dispatcher<RequestReservationCommand>>());         messageDispatcher.Subscribe(k.Resolve<Dispatcher<SoldOutEvent>>());         return messageDispatcher;     }));   container.Register(Component     .For<IQuickening>()     .ImplementedBy<RequestReservationCommand.Quickening>()); container.Register(Component     .For<IQuickening>()     .ImplementedBy<ReservationAcceptedEvent.Quickening>()); container.Register(Component     .For<IQuickening>()     .ImplementedBy<ReservationRejectedEvent.Quickening>()); container.Register(Component     .For<IQuickening>()     .ImplementedBy<CapacityReservedEvent.Quickening>()); container.Register(Component     .For<IQuickening>()     .ImplementedBy<SoldOutEvent.Quickening>());   container.Register(Component     .For<QueueConsumer>());   container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel)); This is actually more verbose than before - almost double the size of the Poor Man's DI example. To add spite to injury, this is no longer strongly typed in the sense that you'll no longer get any compiler errors if you change something, but a change to your classes can easily lead to a runtime exception, since something may not be correctly configured. This example uses the Registration API of Castle Windsor, but imagine the horror if you were to use XML configuration instead. Other DI Containers have similar Registration APIs (apart from those that only support XML), so this problem isn't isolated to Castle Windsor only. It's inherent in the Explicit Register style. I can't claim to be an expert in Java, but all I've ever heard and seen of DI Containers in Java (Spring, Guice, Pico), they don't seem to have Registration APIs much more sophisticated than that. In fact, many of them still seem to be heavily focused on XML Registration. If that's the case, it's no wonder many software thought leaders (like Dan North with his 'new' is the new 'new' line) dismiss DI Containers as being essentially pointless. If there weren't a more sophisticated option, I would tend to agree. Example: Convention over Configuration This is still the same example as before, but now in a state (git tag: services-by-convention-in-daemon; git commit ID: 0a7e6f246cacdbefc8f6933fc84b024774d02038) where almost the entire configuration is done by convention. container.AddFacility<ConsumerConvention>();   container.Register(Component     .For<IObserver<object>>()     .ImplementedBy<CompositeObserver<object>>());   container.Register(Classes     .FromAssemblyInDirectory(new AssemblyFilter(".").FilterByName(an => an.Name.StartsWith("Ploeh.Samples.Booking")))     .Where(t => !(t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Dispatcher<>)))     .WithServiceAllInterfaces());   container.Kernel.Resolver.AddSubResolver(new ExtensionConvention()); container.Kernel.Resolver.AddSubResolver(new DirectoryConvention(container.Kernel)); container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel));   #region Manual configuration that requires maintenance container.Register(Component     .For<DirectoryInfo>()     .UsingFactoryMethod(() =>         new DirectoryInfo(@"..\..\..\BookingWebUI\Queue").CreateIfAbsent())     .Named("queueDirectory")); container.Register(Component     .For<DirectoryInfo>()     .UsingFactoryMethod(() =>         new DirectoryInfo(@"..\..\..\BookingWebUI\SSoT").CreateIfAbsent())     .Named("ssotDirectory")); container.Register(Component     .For<DirectoryInfo>()     .UsingFactoryMethod(() =>         new DirectoryInfo(@"..\..\..\BookingWebUI\ViewStore").CreateIfAbsent())     .Named("viewStoreDirectory")); #endregion It's pretty clear that this is a lot less verbose - and then I even left three explicit Register statements as a deliberate decision. Just because you decide to use Convention over Configuration doesn't mean that you have to stick to this principle 100 %. Compared to the previous example, this requires a lot less maintenance. While you are working with this code base, most of the time you can concentrate on adding new functionality to the software, and the conventions are just going to pick up your changes and new classes and interfaces. Personally, this is where I find the best tradeoff between the value provided by a DI Container versus the cost of figuring out how to implement the conventions. You should also keep in mind that once you've learned to use a particular DI Container like this, the cost goes down. Summary Using a DI Container to compose object graphs by convention presents an unparalled opportunity to push infrastructure code to the background. However, if you're not prepared to go all the way, Poor Man's DI may actually be a better option. Don't use a DI Container just to use one. Understand the value and cost associated with it, and always keep in mind that Poor Man's DI is a valid alternative. This blog is totally free, but if you like it, please buy me a cup of coffee. [Less]