How to register type as specific interface by scanning local exe or assembly

StackOverflow https://stackoverflow.com/questions/22175108

  •  03-06-2023
  •  | 
  •  

Frage

I understand that i can use reflection to scan and register components? Is this what it called scanning in the help/wiki?

  var builder = new ContainerBuilder();
  builder.RegisterType<GeneralHtmlNotifier>().As<INotifier>();
  builder.RegisterType<DiskSystemNotifier>().As<INotifier>();
  builder.RegisterType<DatabaseSizesNotifier>().As<INotifier>();
  builder.RegisterType<GeneralTextFileNotifier>().As<INotifier>();
  builder.RegisterType<DiskSystemTextNotifier>().As<INotifier>();
  builder.RegisterType<DatabaseSizesTextNotifier>().As<INotifier>();
  builder.RegisterType<DiskSystemHierarchyNotifier>().As<INotifier>();
  builder.RegisterType<DatabaseSizeHierarchyNotifier>().As<INotifier>();
  builder.Build();

I want to "scan" my local exe for INotifier and register. Don't really understand how I call write the code.

 var dataAccess = Assembly.GetExecutingAssembly();

 builder.RegisterAssemblyTypes(dataAccess)
    .Where(t => t.Name.EndsWith("Repository"))
 .AsImplementedInterfaces();

Is this what i'm looking for.

War es hilfreich?

Lösung

This is what I use in general, so it makes sure to implement specific interface and gets rid of abstract classes (if any):

builder.RegisterAssemblyTypes(dataAccess)
         .Where(t => (typeof(INotifier).IsAssignableFrom(t) && t.IsClass && !t.IsAbstract))
         .AsSelf()
         .AsImplementedInterfaces();
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top