Kaine
Kaine

Reputation: 1287

Is is possible to use Ninject on an EntityFramework Entity object?

I'm not sure if this is possible, but I'd like to have a class that can be loaded and saved using Entity Framework which also uses Ninject to populate Interfaces with concrete implementations at run time.

I started with a constructor like this:

    public FancyObject(ICatProvider kitty)
    {
        this.kitty = kitty;
    }

This works as far as Ninject goes, we get a Cat - and it works for saving the entity to SQLServer using Entity Framework. However, it fails when trying to load the entity because Entity Framework needs a parameterless constructor.

So I tried putting it on a property like this:

    [Inject]
    public ICatProvider kitty { get; set; }

    public FancyObject()
    {
    }

This can load from the DB, but Kitty is always null.

All I have in the bindings is:

    kernel.Bind<ICatProvider>().To<FancyFileBasedCat>();

I'm guessing this is because I'm using the Entity Framework to create the entities and so Ninject isn't getting a look in.

Am I missing something obvious here? Is there a nice way to do this?

Upvotes: 3

Views: 364

Answers (1)

nemesv
nemesv

Reputation: 139758

Your guess is right. Your property is null because:

"using the Entity Framework to create the entities and so Ninject isn't getting a look in."

However you can use the Kernel.Inject method (wiki) to inject dependencies to existing instances:

var fancyObject = db.GetFancyObject();
kernel.Inject(fancyObject);
// fancyObject.kitty should be filled in.

Entities having dependencies usually is a code smell and maybe you should rethink your design. There are lots of way to avoid dependencies in entities like:

  • Passing the service when it is needed:

    public class FancyObject
    {
         public Result MethodWorkingWithCats(int somearg, ICatProvider kitty)
         {
              reuturn DoSoemThing(this, somearg, kitty)
         }
    }
    
  • Create a FancyObjectService which dependy on the ICatProvider and works on/with FancyObject
  • etc.

Upvotes: 5

Related Questions