Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Property Injection in MVC Core and AutoFac

I can use Constructor Parameter Injection easily In MVC Core. But Property Injection is not supported.I try use AutoFac but fail too.
So how to use Property Injection in MVC Core.
Here is the code with AutoFac

services.AddMvc();
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<Test2>().As<ITest>();
builder.RegisterType<HomeController>().PropertiesAutowired();
builder.Populate(services);
var container = builder.Build();
//The following code works
HomeController test2 = container.Resolve<HomeController>();
return new AutofacServiceProvider(container); 
like image 361
Siying Wang Avatar asked May 23 '18 04:05

Siying Wang


1 Answers

In dotnet core, you need to make the following changes to make Autofac work: Add a public Autofac IContainer in your application Startup.cs

public IContainer ApplicationContainer { get; private set; }

Change ConfigureServices in Startup.cs to return IServiceProvider, do all your registrations, populate the framework services in your container by using builder.Populat(services);. Please note that there is no need for you to do builder.RegisterType<HomeController>().PropertiesAutowired();

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    builder.Populate(services);
    ApplicationContainer = container;
    return new AutofacServiceProvider(ApplicationContainer);
}

You will also need to make sure you dispose the container on application stopped by doing this in your Configure method.

public void Configure(IApplicationBuilder app, IApplicationLifetime appLifetime)
{
    app.UseMvc();           
    appLifetime.ApplicationStopped.Register(() => ApplicationContainer.Dispose());
}

After you do this - your controllers should automatically get the properties autowired.

like image 136
Hiral Desai Avatar answered Nov 14 '22 23:11

Hiral Desai