Z
Z
zergon3212019-12-31 14:13:15
ASP.NET
zergon321, 2019-12-31 14:13:15

Why doesn't Property injection work in ASP.NET Core MVC via Autofac?

I have an ILol interface and a Lol class that implements it, as well as a controller:

public class UniversityController : Controller
    {
        public ILol Lol { get; set; }

        public IActionResult Index()
        {
            ViewData["Header"] = "Hello, world!";
            ViewData["NullCheck"] = Lol == null ? "It's null" : Lol.GetLol();

            return View();
        }
    }

This is what part of my Startup class looks like:
Dependency injection code
public IContainer ApplicationContainer { get; private set; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            // Dependency resolving.
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            
            ContainerBuilder builder = new ContainerBuilder();
            
            builder.RegisterType<Lol>().As<ILol>().PropertiesAutowired().InstancePerLifetimeScope();
            builder.Populate(services);

            IContainer container = builder.Build();

            ApplicationContainer = container;

            return new AutofacServiceProvider(container);
        }

However, dependency injection doesn't work and the Lol property on the controller class remains null . However, dependency injection through the constructor works. What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
basrach, 2019-12-31
@basrach

.RegisterType().As().PropertiesAutowired()

By this, you said that you want Autofac, when creating an instance of a class Lol, to inject into all of its (Lol object) public properties. To make your example work, you need to do the same but for the UniversityController.
And generally it is better not to use an injection through properties. Never.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question