0

I've got the following bit of (simplified) code:

public abstract class BaseClass
{
  [Dependency]
  public IRequiredService RequiredService { get; set; }

  protected string RequiredParameter { get; private set; }

  public BaseClass(string requiredParameter)
  {
    this.RequiredParameter = requiredParameter;
  }
}

public class DerivedClass : BaseClass
{
  public DerivedClass(string requiredParameter) : base(requiredParameter)
  {
    RequiredService.DoSomething(); //this will fail!
  }
}

In other words, I'd like to have access to the Unity-filled RequiredService in the constructor... but that's impossible, since that property hasn't been filled by Unity yet. I COULD add the IRequiredService as a required constructor parameter, but then I'd need to refactor every constructor of every derived class to also include that parameter.

I was wondering if there's a better way.

In short, I'd like to run a bit of code after a class has been constructed and after unity has filled all the class' properties marked with the [Dependency] attribute.

Is there a simple way to do this?

2
  • Have you considered putting RequiredService.DoSomething(); inside a [InjectionMethod] call instead of the constructor? Commented Apr 6, 2017 at 15:30
  • @ScottChamberlain Excellent suggestion. I must have missed that attribute. Feel free to turn this into an official answer, and I'll accept it. Commented Apr 7, 2017 at 7:57

1 Answer 1

1

Instead of putting RequiredService.DoSomething(); in the constructor you can put it in a inside a [InjectionMethod] call, this will allow you to reliably know that RequiredService has been populated.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.