Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically register interface to class in autofac

Tags:

c#

autofac

Project I'm working on, each class has its own interface with the following naming conventions

ClassA.cs : IClassA.cs

ClassB.cs : IClassB.cs etc

Currently in the bootstrapper for Autofac I am repeatedly putting

builder.RegisterType<ClassA>.As<IClassA>();
builder.RegisterType<ClassB>.As<IClassB>();

With a few singletons thrown around for good measure.

Is there any way to automate the binding process? i know it's not a huge amount of extra effort adding the bindings manually, but it'll get worse as time goes on I'm sure.

I've currently got the following in my container

builder.RegisterType<MyClass>().As<IMyClass>().SingleInstance();

var myAss = Assembly.GetExecutingAssembly();
builder.RegisterAssemblyTypes(myAss)
   .Where(t => t.IsClass )
   .As(t => t.GetInterfaces().Single(i => 
   ( i.Name.Length == t.Name.Length + 1 ) && 
   ( i.Name == "I" + t.Name)));

However looking at the watch window for builder. It looks as though it may be registering Myclass twice. Now I may be completely wrong here as I cannot for the life of me find what's actually being registered in builder by the watch window.

If I am wrong please just give me a slap.

like image 817
user3265613 Avatar asked Feb 07 '23 06:02

user3265613


1 Answers

However looking at the watch window for builder. It looks as though it may be registering Myclass twice.

Yes this is true, since you are registering the class MyClass manually as singleton (first line) and a second time in the RegisterAssemblyTypes call.

I think registering all your classes this way is pretty risky, since it will fail every time you have a class without an implemented interface or if the interface does not follow your naming convention. Doing something like

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

as shown in the Autofac docs will probably be more robust. And if you simply want to register all your classes you can skip the Where part.

like image 96
fknx Avatar answered Feb 14 '23 04:02

fknx