Wednesday, April 1, 2020

Use Autofac for IoC in .NET Core.

At: Tools > NuGet Package Manager > Manage NuGet Packages for Solution... ...search for "Autofac.Extensions.DependencyInjection" at the "Browse" tab. You will need the Autofac and Autofac.Extensions.DependencyInjection using declarations. Per this, the ConfigureServices method in Startup must change like so:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
   services.AddControllers();
   var builder = new ContainerBuilder();
   builder.RegisterModule(new Foo());
   builder.RegisterModule(new Bar("bar"));
   builder.RegisterModule<Baz>();
   builder.RegisterType<Qux>().As<IQux>().WithParameter(new
         TypedParameter(typeof(IServiceFactory), new ServiceFactory(new[] { new
         FilenetProvider() })));
   builder.RegisterType<Yin>().As<IYin>();
   builder.RegisterType<Yang>().As<IYang>().SingleInstance();
   builder.Populate(services);
   var container = builder.Build();
   return new AutofacServiceProvider(container);
}

No comments:

Post a Comment