2

EF requires parameterless constructor but is it possible to override this some how?

public class MyModelClass
{
   ADependency _a;
   public MyModelClass(ADependency a)
   {
      _a = a;
   }
   ...
}

So when the client does a query like:

var myModelClasses = context.MyModelClasses;

each class gets created with the dependent instance injected.

2
  • 1
    Your class can have as many constructors as you want. Commented Aug 19, 2011 at 12:39
  • @Joe: yes but I need the dependency to get injected when the model object is created regardless of how it's created. I'll clarify the question. Commented Aug 19, 2011 at 12:47

2 Answers 2

2

You could use the empty constructor and use the DependencyResolver and do it IN the constructor.

public class MyModelClass
{
   ADependency _a;
   public MyModelClass()
   {

            _a = DependencyResolver.Current.GetService<_a>();
   }
   ...
}
Sign up to request clarification or add additional context in comments.

3 Comments

good suggestion, however I'm looking for a way to actually inject the dependency into the constructor.
@Christian this solution introduces another set of problems. Now you have hidden dependency with a singleton/static instance. Unit testing and refactoring will be difficult.
@Eranga, yes I realize this, but it's perhaps better than new up the dependency directly?
2

No it is not possible to override. EF have to use parameterless constructor and this behaviour cannot be changed because there is no way to use custom factories. You can either use the solution with service locator pattern mentioned by @Kevin or you can handle ObjectMaterialized event and set the dependency through the property of your entity.

1 Comment

thanks, I guess Kevin deserves the 'accepted answer' credit then.

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.