Search code examples
.netautofac

Autofac replacing MEF Extensions get the list of services by the address of a directory


Well I need to remove MEF extensions from my code when initializing the service, I saw that autofac is a good alternative I was looking at it recently I am using version 5.2 of autofac, about mi code... when using Dim catalog As New AggregateCatalog is for get a list of services that I want to initialize, after.

After this I add the services in the list catalog.Catalogs.Add(New DirectoryCatalog(applicationDirectory)).

finally the services are initialized as in the code below, as a goal I have to completely change the IoC and remove the libraries:

Imports System.ComponentModel.Composition.Hosting

Imports System.ComponentModel.Composition

my question is, what is the autofact alternative to do this process of adding the libraries by assigning a directory address? is a visual basic function:

<ImportMany(GetType(Team.Services.IServiceProvider))>
Protected Property Services As List(Of IServiceProvider)

Public Sub StartServices(applicationDirectory As String) 'As List(Of IServiceProvider)
        Dim catalog As New AggregateCatalog

        Me.applicationDirectory = applicationDirectory

        catalog.Catalogs.Add(New DirectoryCatalog(applicationDirectory))

        Dim container As New CompositionContainer(catalog)

        container.ComposeParts(Me)

        If Me.Services IsNot Nothing Then

            'For Each service In Me.Services
            'multi threaded
            Parallel.ForEach(Of IServiceProvider)(Me.Services, Sub(service)
                                                                   service.StartService()
                                                               End Sub)
        End If

    End Sub

Solution

  • What you're (basically) doing by providing the directory there is:

    • Loading some assemblies
    • Registering types from those assemblies

    Autofac does not do assembly loading. You will need to look at other docs for how to load assemblies for your app. This is actually a really complex thing depending on app type and framework target.

    If you can get the assemblies loaded, though, Autofac can register types from them, and there is a lot of documentation and examples out there for assembly scanning.

    Unfortunately, though, it's not a "one stop shop" for loading and registration, though. You'll find that to generally be the case for all DI frameworks nowadays because that assembly loading question has so many potential answers.