Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofac register assembly types

Tags:

In Castle, I used to do the following to register types from a different assembly:

Classes.FromAssemblyNamed("MyServer.DAL")
       .Where(type => type.Name.EndsWith("Repository"))
       .WithServiceAllInterfaces()
       .LifestylePerWebRequest(),

In Autofac, I change the above code to this:

builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
       .Where(t => t.Name.EndsWith("Repository"))
       .InstancePerRequest();

Is it correct?

like image 395
Ivan-Mark Debono Avatar asked Nov 10 '14 07:11

Ivan-Mark Debono


People also ask

How do I register an Autofac interface?

Register by Type var builder = new ContainerBuilder(); builder. RegisterType<ConsoleLogger>(); builder. RegisterType(typeof(ConfigReader)); When using reflection-based components, Autofac automatically uses the constructor for your class with the most parameters that are able to be obtained from the container.

Which of the following option is used in automatic types of registration in order to scan an assembly and automatically register its types by convention?

Use Autofac as an IoC container API Web API project with the types you will want to inject. Autofac also has a feature to scan assemblies and register types by name conventions.

What is AsImplementedInterfaces?

RegistrationExtensions. AsImplementedInterfaces MethodSpecifies that a type from a scanned assembly is registered as providing all of its implemented interfaces.


2 Answers

This is the correct way:

builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
       .Where(t => t.Name.EndsWith("Repository"))
       .AsImplementedInterfaces()
       .InstancePerRequest();
like image 99
Ivan-Mark Debono Avatar answered Sep 19 '22 03:09

Ivan-Mark Debono


For UWP correct way is a bit alter:

   var assemblyType = typeof(MyCustomAssemblyType).GetTypeInfo();

   builder.RegisterAssemblyTypes(assemblyType.Assembly)
   .Where(t => t.Name.EndsWith("Repository"))
   .AsImplementedInterfaces()
   .InstancePerRequest();

For each assembly you have take single type that belongs assembly and retrieve assembly's link from it. Then feed builder this link. Repeat.

like image 22
Ingerdev Avatar answered Sep 20 '22 03:09

Ingerdev