DbContext类的依赖注入

时间:2013-12-07 21:13:57

标签: asp.net-mvc dependency-injection unity-container

我是Dependency Injeection的新手,并使用“Unity Mvc”作为我的DI容器。我有一个ProductRepository类,它使用我的dbContext类来获取数据,但是我想注册我的dbContext。这就是我的......

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()

这是我的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

我需要做什么,所以在我的回购中我可以避免创建dbContect类的新实例?

1 个答案:

答案 0 :(得分:2)

将用C#语法回答,好吗?

为您的上下文创建一个界面:

public interface IWebSolutionEntities
{
}

public class WebSolutionEntities : IWebSolutionEntities
{
   ...
}

并将一个构造函数添加到存储库,这取决于此接口:

public class ProductsRepository : IProductsRepository
{
    private IWebSolutionEntities _db;

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

控制器依赖于存储库接口:

public class ProductsController : Controller
{
    private IProductsRepository _productsRepository;

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

然后,您需要在global.asax中注册依赖项解析器:

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

之后,UnityDependencyResolver实例将创建控制器。