Search code examples
c#dependenciesinversion-of-controlautofaccode-injection

Autofac. Base Class properties resolved without specific injection


I'm looking for a possible solution to the following.

I have a base class that has a dependency which I currently use property injection to satisfy.

public class BaseClass {
    IService SomeService { get; set; }
}

I have multiple classes which inherit from this base class.

public class DerivedClass : BaseClass, IDerivedClass {

}

And I inject using the following.

builder.RegisterType<DerivedClass>().As<IDerivedClass>().OnActivated(e => e.Instance.SomeService = e.Context.Resolve<IService>());

I do this for about 12 other classes which extend the base class. Is there a way so that any class extending BaseClass will get my IService registration without setting up an Activation event for each registration? It's working fine like this, but would just like to clean up the registrations.


Solution

  • Ten years later now you can use the required property to enable auto injection without parameters in constructor: https://autofac.readthedocs.io/en/latest/register/prop-method-injection.html#required-properties