简体   繁体   中英

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.

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>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM