0

My processor is defined as follows:

<processor type="MyProject.MyProcessor, MyProject" resolve="true" />

I have then defined my Configurator Class:

<sitecore>
    <services>
        <configurator type="MyProject.MyConfiguratorClass, MyProject" />
    </services>
</sitecore>

And inside MyConfiguratorClass I will do something like

public void Configure(IServiceCollection serviceCollection) {
    serviceCollection.AddSingleton<classType>(somethingElse);
}

Question

The Processor that I want to inject to implements an Abstract class with a Constructor that is already defined and has its own parameters. How can I inject another dependency - say, an instance of the class MyProject.InjectedClass in it?

6
  • An abstract class (with constructor) could never be instantiated. The inheriting class would need to implement it's own constructor and call base(base args). The inheriting constructor should ask for the dependency.
    – Mark Cassidy
    Jul 29 '19 at 14:20
  • Yes, of course the MyProject.MyProcessor class implements that constructor. I'm still unsure how should I perform the serviceCollection.AddSingleton() call in order to allow MyProject.MyProcessor to access an instance of injected class. Jul 29 '19 at 14:23
  • 1
    It would just ask for it.... ? :D By that I mean in it's constructor.
    – Mark Cassidy
    Jul 29 '19 at 14:28
  • There is clearly something that I am missing. If the Constructor in the Abstract class has already 3 parameters, and I cannot change the signature when implementing the Constructor, how can I sneak in a 4th parameter with my injected class? Jul 29 '19 at 14:31
  • 1
    public MyInheitedClass(IString a1, string a2, string a3, string a4) : base(a2, a3, a4)
    – Mark Cassidy
    Jul 29 '19 at 14:45
2

You've not shared the actual classes in question, so I have to extrapolate.

But if you have

public abstract ClassA
{
    public ClassA(IDependency dependencyOne)
    {
         ...
    }
}

public ClassB : ClassA
{
    public ClassB(IDependency dependencyOne, string connectionStringName) : base(dependencyone)
    {
        ...
    }
}

Then this would be one example of how it can be done. Since the abstract class does not have a parameterless constructor, your constructor HAS to derive base on all of its constructors.

If you're not using interfaces but instead the abstract type, none of this really changes. You can do:

serviceCollection.AddSingleton<ClassA>(ClassB);

Assuming there is another mapping in place for IDependency.

-1

If the inherited class constructor has more parameters than its base class constructor we can use the below syntax.

public inheritedClass(param p1, param p2, param p3):base(p1, p2){}

Thanks, Akif

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.