Auto resolution and Dependency Injection

Rather than implementing a class that declares all of your dependency injection registrations you can implement a piece of code that will work through your application and automatically register any class identified by a particular interface (usually a blank interface used exclusively for this purpose.

Blank interface:


namespace Library.Initialisation
{
   /// 
   /// Interface IAutoRegisterAsTransient. Use it to mark a class as discoverable and register in the container as a transient
   /// 
   public interface IAutoRegister 
   {
   }
}

The Magic registration:


/// 
/// Discovers and register types.
/// 
private void DiscoverAndRegisterTypes(IDependencyResolver dependencyResolver)
{
   using (new InformationLogEventWriter())
   {
      var types = ReflectionHelper.GetAllTypes(t => !t.IsAbstract && !t.IsInterface && typeof(IAutoRegister).IsAssignableFrom(t));

      foreach (var t in types)
      {
         dependencyResolver.RegisterType(t, Lifetime.Transient);
      }
   }
}

Leave a Reply

Your email address will not be published. Required fields are marked *