Reputation: 371
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
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
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