highwingers
highwingers

Reputation: 1669

Dependency injection for DbContext Class

I am super new to Dependency Injeection and using "Unity Mvc" as my DI container. I have a ProductRepository Class which is using my dbContext class to get data, however I would love to register my dbContext. here is what I have...

Partial Public Class websolutionsEntities
    Inherits DbContext
' Code for dbContext Class

' This is my Repo, which I want to fix
Public Class productsRepository
    Implements IProductRepository

    ' This line below I want to avoid, I dont want to rely on my dbContext for all repo's

    Private _db As websolutionsEntities = New websolutionsEntities()

and here is my Unity Bootstrap:

Private Shared Function BuildUnityContainer() As IUnityContainer
    Dim container = New UnityContainer()

    ' register all your components with the container here
    ' e.g. container.RegisterType<ITestService, TestService>();       
    container.RegisterType(Of IProductRepository, productsRepository)()


    Return container

End Function

What do i need to do, so in my Repo i can avoid creating a new instance of dbContect class?

Upvotes: 0

Views: 2183

Answers (1)

nativehr
nativehr

Reputation: 222

Will answer with C# syntax, ok?

Make an interface for your context:

public interface IWebSolutionEntities
{
}

public class WebSolutionEntities : IWebSolutionEntities
{
   ...
}

And add a constructor to the repository, that depends on this interface:

public class ProductsRepository : IProductsRepository
{
    private IWebSolutionEntities _db;

    public ProductsRepository(IWebSolutionEntities db)
    {
        _db = db;
    }
}

A controller depends on the repository interface:

public class ProductsController : Controller
{
    private IProductsRepository _productsRepository;

    public ProductsController(IProductsRepository _productsRepository)
    {
        productsRepository = _productsRepository;
    }
}

Then you need to register a dependency resolver in global.asax:

protected void Application_Start()
{
    DependencyResolver.SetResolver(new UnityDependencyResolver(UnityBootstrap.BuildUnityContainer()));
}

After that controllers will be created by the UnityDependencyResolver instance.

Upvotes: 2

Related Questions