Search code examples
c#inversion-of-control

Resolve IoC interface to class with same name implicitily


Given a set of interfaces where for each interface there is a corresponding implementing class with the same name (e.g.: ISomeThing : SomeThing), is there a way to automatically resolve all without creating explicit mappings?

There is probably an IoC container that has this already..


Solution

  • This is default convention for StructureMap. It tries to connect concrete classes to interfaces using the I[Something]/[Something] naming convention.

        public interface ISpaceship { }
    
        public class Spaceship : ISpaceship { }
    
        public interface IRocket { }
    
        public class Rocket : IRocket { }
    
        [Fact]
        public void default_scanning_in_action()
        {
           var container = new Container(_ =>
           {
               _.Scan(x =>
               {
                x.Assembly("<AssemblyNameWhereClassesAreDefined>");
                x.WithDefaultConventions();
               });
           });
    
           var spacesfip = container.GetInstance<ISpaceship>().ShouldBeOfType<Spaceship>();
           var rocket = container.GetInstance<IRocket>().ShouldBeOfType<Rocket>();
        }