Christian
Christian

Reputation: 229

How can I Inject Behavior into Entity Framework Object Constructors?

If I have an entity EntityA, which is an Entity Framework object, how would I go about injecting different behavior at time of creation?

These particular entities need to utilize a different strategy for some calculations. I would like to use DI to supply the correct strategy when the object is created. Is there any way to intercept?

Added: i thinking on the two patterns below (just pseudo to get the point across).

        public partial class Entity
    {
          public Entity(ICalculationStrategy strategy)
          {
              _calcStrategy = strategy;
          }
    }

public partial class Entity
        {
              public Entity(ICalculationFactory factory)
              {
                  _calcStrategy = factory.ProvideCalculator(this);
              }
        }

Upvotes: 2

Views: 1029

Answers (2)

Thorarin
Thorarin

Reputation: 48476

EntityObjects don't have any constructor defined in their generated code, so you can just add one in a partial class:

public partial class MyEntity
{
    public MyEntity()
    {
         // Whatever logic to determine your strategy
    }
}

How you would go about doing your calculations differently, depends on what exactly you're trying to do. If you want to pass extra parameters to the constructor somehow, I don't think you can, so you'll have to work around that.

Also, have you looked at inheritance in Entity Framework? Based on the value of some column / property, you can have it use a different subclass, which can have different implementations of various business logic, through the use of partial classes with abstract and/or virtual methods and properties.

Of course, you could change the behavior after the object is instantiated, but I get the feeling that isn't what you want? Could you access the factory in a static way? Either as a static class, method or property?

MyFactory.Current = new MyFactory(parameters);

public partial class MyEntity
{
    public MyEntity()
    {
        _calcStrategy = MyFactory.Current.ProvideCalculator(this);
    }
}

Upvotes: 1

Andrew Peters
Andrew Peters

Reputation: 11323

Can you pass in the strategy at the time the calculation is performed?

myEntity.Calculate(myStrategy);

How about invert the relationship between the strategy and the entity?

myStrategy.Calculate(myEntity);

Or, DI the strategy using property injection?

Upvotes: 2

Related Questions