Muhammed Irshad
Muhammed Irshad

Reputation: 92

Using Dependency injection to initialise Entity Framework model?

So i started looking into Dependency Injection and Ioc Containers. From what i know DI is used to avoid tighly coupling the classes or avoid creating the depending object out of the consumer class. But isnt it unnecessary to use DI if we are using that object only in one class? Now my problem is how do i initialize my Entity model with unity? Currently i use constructor injection as usual to initialise my Entity model as

public class Food
{
    private FoodContext _foodContext

    public Food(FoodContext food)
    {
        _foodContext=food
    } 
}

Now here FoodContext is my entity framework model, how do I initialise with unity? I may want to replace the model with another in future, so it may become a headache to find and replace all the reference across the entire solution. So in order for doing that, am I going to create an interface first? I mean that autogenerated class contains lots and lots of properties and methods. that doesn't seem right.

So what is the normal practice of doing this?

Upvotes: 1

Views: 3267

Answers (1)

HichemSeeSharp
HichemSeeSharp

Reputation: 3318

To achieve that, take a look at the Repository pattern The main Idea of Repository pattern : It abstracts the DataProvider using an interface and called using dependency injection that leads to two main benefits : Low coupling and Testability.

Upvotes: 1

Related Questions