Paul Connolly
Paul Connolly

Reputation: 371

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.

Upvotes: 1

Views: 1099

Answers (2)

n0099
n0099

Reputation: 1323

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

Upvotes: 1

Ph0en1x
Ph0en1x

Reputation: 10067

Just use constructor injection. Create constructor with parameters for your class like

public DerivedClass(IServiceOne service1, IService2 service2)
{
this._service1 = service1;
this._service2 = service2;

}

and make autofac doing his job automatically, like

builder.RegisterType<T>();

Upvotes: 1

Related Questions