Property injection requires some additional setup. Let's Assume in your case we have this hierarchy of classes:
public class HomeController
{
public ITest Test {get; set;}
}
public class Test : ITest
{
public IRepository Repository {get;set;}
}
public class Repository: IRepository
{
}
The first things needed to be done are changing the return type to IServiceProvider for ConfigureServices(IServiceCollection services)
and building new container using Populate
method from 'Autofac.Extensions.DependencyInjection' method in order to return AutofacServiceProvider
New ConfigureServices method:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddControllersAsServices();
ContainerBuilder builder = new ContainerBuilder();
builder.Populate(services);//Autofac.Extensions.DependencyInjection
/*Here we are going to register services for DI*/
return new AutofacServiceProvider(builder.Build());
}
Next step is registration of classes in DI container. Property-injection for 'service classes' requires less action than for 'controllers'.
To setup property injection for service classes you just need to:
- Register type in the container:
builder.RegisterType<Repository>().As<IRepository>();
- Register type in which you are going to inject dependencies through
properties with PropertiesAutowired():
builder.RegisterType<Test>.As<ITest>().PropertiesAutowired()
To setup property injection for a controllers you need a little more steps:
- Execute
AddControllersAsServices()
on services.AddMvc()
Regiser DI for controllers with call of PropertiesAutowired()
for all controllers:
//in case you just need to allow registration for several specific controllers change this line
var controllersTypesInAssembly = typeof(Startup).Assembly
.GetExportedTypes()
.Where(type => typeof(ControllerBase).IsAssignableFrom(type)).ToArray();
builder.RegisterTypes(controllersTypesInAssembly).PropertiesAutowired();
As a result here is ConfigureServices() for predetermined hierarchy:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddControllersAsServices();
ContainerBuilder builder = new ContainerBuilder();
builder.Populate(services);//Autofac.Extensions.DependencyInjection
builder.RegisterType<Repository>().As<IRepository>()
.InstancePerLifetimeScope();
var controllersTypesInAssembly = typeof(Startup).Assembly.GetExportedTypes()
.Where(type => typeof(ControllerBase).IsAssignableFrom(type)).ToArray();
builder.RegisterTypes(controllersTypesInAssembly).PropertiesAutowired();
builder.RegisterType<Test>().As<ITest>().PropertiesAutowired();
return new AutofacServiceProvider(builder.Build());
}