Search code examples
.netowinautofac

How can I register a service collection against .Net Framework and Autofac?


I'm trying to add this Microsoft.FeatureManagement service package into my .NET Framework 4.7 web API. The application is configured to use the OWIN pipeline and Autofac DI. All services are registered against the Autofac IContainerBuilder.

The Feature Management service registration extends IServiceCollection and while it's a .NET Standard 2.0 library, it looks like it's designed to be used against .NET Core DI service registration. For example, the setup expects registration to look like this:

public void Configuration(IServiceCollection services) {
  services.AddFeatureManagement();
}

Is there a way I can register this with my current Autofac + Framework?

Running on .NET Framework 4.7 and using Autofac 4.9.2, here is my current configuration:

CustomModule.cs

public class CustomModule: Module {
  protected override void Load(ContainerBuilder builder) {
    builder.RegisterType<ExampleType>().As<IExampleType>();
  }
}

Startup.cs

public void Configuration(IAppBuilder app) {
  var configuration = new HttpConfiguration();
  var containerBuilder = new ContainerBuilder();
  containerBuilder.RegisterModule(new CustomModule());
  containerBuilder.RegisterWebApiFilterProvider(configuration);
  var container = containerBuilder.Build();
  configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

  app.UseAutofac(container, configuration);
}

Solution

  • Use Autofac.Extensions.DependencyInjection. There's a builder.Populate(IServiceCollection) extension that does exactly that.