Autofac Scan for Various Applications

Suppose you are working on an ASP.NET MVC project, and these are layers divided into different projects in one solution. Each project has autofile modules created to connect dependencies. Now I would like to scan assemblies and register all modules in the container.

I adapted an extension method similar to what was distributed here http://goo.gl/VJEct

public static void RegisterAssemblyModules(this ContainerBuilder builder, Assembly assembly) { var scanningBuilder = new ContainerBuilder(); scanningBuilder.RegisterAssemblyTypes(assembly) .Where(t => typeof(IModule).IsAssignableFrom(t)) .As<IModule>(); using (var scanningContainer = scanningBuilder.Build()) { foreach (var m in scanningContainer.Resolve<IEnumerable<IModule>>()) builder.RegisterModule(module); } } 

My first question, given that this sample was provided several years ago, is this still a possible design for use with current autofac versions?

Secondly, the MVC application depends on functionality in other layers, which means that sometimes I will need to register types using .InstancePerHttpRequest (). However, I would also like to be able to link to them from non-web applications and not be dependent on System.Web. What is the best approach for registering modules that can be used in these different contexts?

+3
source share
1 answer

I would not register the modules in the container. I see no reason for this.

Here is an alternative.

It uses Activator.CreateInstance to create modules and register them in the builder.

The same structure also provides you with free registration support. Just add the attribute to your services:

 [Component] public class MyService : IService { } 

And run the builder extension method:

 builder.RegisterAllComponents(Assembly.GetExecutingAssembly()); 
0
source

Source: https://habr.com/ru/post/918401/


All Articles