Wrapper configuration with StructureMap
Recently we have some problems with StructureMap configuration.
We decided to move away from xml files and use registry configuration.
Imagine the following scenario, we have a service class (MyService), and decide
to create simple caching mechanism, by creating a wrapper class (MyServiceWithCaching)
public interface IService { List<string> MyMethod(); } // Original service public class MyService : IService { public List<string> MyMethod() { ... } } // Service that supports simple caching public class MyServiceWithCaching : IService { IService _service; List<string> _cached; // NOTE: We want IService to be injected by IoC container public MyServiceWithCaching(IService service) { _service =service; } public List<string> MyMethod() { if (_cached == null) { // call original when no cached data _cached = _service.MyMethod(); } return _cached; } }
The problem is how to tell StructureMap that when somebody asks for IMyService it should get MyServiceWithCaching which should be injected with original MyService class.
It took us some time to figure this out and here’s the solution:
public class IocRegistry : Registry { protected override void configure() { this.BuildInstancesOf<imyService>() .TheDefaultIs( Instance<imyService>() .UsingConcreteType<myServiceWithCaching>() .Child<imyService>() .IsConcreteType<myService>() ); base.configure(); } } ;