October 15, 2013

ServiceStack IOC Autowiring by Convention

A situation came up where we wanted to implement a convention to auto-wire many of our classes using ServiceStack IOC. Basically we wanted to eliminate the need to hard-code mappings over and over for every class in a bootstrap file.

For example we wanted to avoid this:

container.RegisterAutoWiredAs<MyType1,IMyType1>();
container.RegisterAutoWiredAs<MyType2,IMyType2>();
container.RegisterAutoWiredAs<MyType3,IMyType3>();
container.RegisterAutoWiredAs<MyType4,IMyType4>();
...

To achieve this we can use .net reflection to scan our assemblies and look for a special interface that represents classes we want to automatically inject. Then we can utilize the ServiceStack IOC method RegisterAutoWiredType to register the types during runtime.

Here's an example where IInjectable is the interface we use to identify which classes will be injected:

June 7, 2013

Dependency Injection of Multiple Objects Same Interface using StructureMap


I have been reading Mark Seemann's excellent book on Dependency Injection & applying what I have been learning to StructureMap.

Often times I have multiple objects that implement the same interface. In the past I may have used an abstract factory to create the instance I needed at a given time based on some sort of key or identifier like so:



However I was interested in using an IOC container like StructureMap to get rid of the ugly switch statement with the factory object. I did so by registering each object in my container and giving it a name with the .Named() method like so:

If you would like to see more please check out a simple example project over at my GitHub called MultipleObjectDemo.

Fun With Strongly Typed Enums!

Nobody likes using plain old boring Enums in C# these days! So why not try using a cool strongly typed Enum instead.