2

I'm building an application with ASP.Net Core 2.1 and I'm using autofac instead the built-in DI container.

Now I have a doubt: if I have a library that provides extension methods for IServiceCollection, how can I use it in autofac?

In my case I would like to add the Refit library to create some REST clients. From the documentation the client should be added in the DI engine with the following extension method

services.AddRefitClient<ICountryRepository>()
                .ConfigureHttpClient(c => c.BaseAddress = new Uri(Configuration.GetSection("Apis:CountryApi:Url").Value));

How can I do the same with autofac? In general is there a way to use the IServiceCollection extension methods in autofac registrations?

I cannot register the dependency in ConfigureService method because my project is divided into several dlls and the registration in this case logically belongs in another dll not referenced. (The division into modules is one of the reasons why I chose Autofac)

Thanks

simone_Vin
  • 55
  • 6
  • 1
    use Service collection with the Autofac integration for DI Core. That way you can have the functionality of Autofac along with the functionality provided by the library – Nkosi Jun 01 '21 at 17:02
  • @Nkosi do you have an example or a links to some resources? – simone_Vin Jun 01 '21 at 17:09
  • 1
    https://autofac.readthedocs.io/en/latest/integration/aspnetcore.html – Nkosi Jun 01 '21 at 17:21
  • @Nkosi thanks but this approach don't work in my case. By design of the architecture the class ICountryRepository can't be referenced from the Startup.cs. I asked if there Is a way to use the extension method in other DLL using the module of Autofac – simone_Vin Jun 01 '21 at 17:59
  • 1
    "By design of the architecture the class ICountryRepository can't be referenced from the Startup.cs." You might want to rethink your architecture. Your Startup is part of the [Composition Root](https://freecontent.manning.com/dependency-injection-in-net-2nd-edition-understanding-the-composition-root/) and the Composition Root depends on [*every* project in the solution](https://stackoverflow.com/questions/9501604/ioc-di-why-do-i-have-to-reference-all-layers-assemblies-in-applications-entry). – Steven Jun 01 '21 at 19:01
  • 1
    @steven From the startup i already start the autofac modules registration. I do this referencing from my webapi project one DLL named "InjectionBootstrapper" that references the modules of the other dlls. I prefer don't reference all the dlls directly from the webapi project. Now i resolved the problem of this post modifing the behaviour of my injectionBootrapper component. I added a new method to add the registration in the IServiceCollection. This new method pass the istance of serviceCollection to all other dlls for add their dependencies. – simone_Vin Jun 01 '21 at 22:55

0 Answers0