使用实体框架在引用的dll中使用存储库

时间:2011-05-17 08:27:31

标签: entity-framework asp.net-mvc-3

我创建了一个 DLL ,其中包含许多我正在尝试在单独项目中使用的身份验证用户管理(MVC) 3网站)。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TestProj.Authentication;

namespace TestSite.MVC.Areas.Admin.Controllers
{
    public class TestController : Controller
    {     
        AuthenticationRepository authrep = new AuthenticationRepository();

        public ActionResult Index()
        {
            authrep.DeleteUser(1);
            return View();
        }
    }
}

现在这显然不起作用,这是可以理解的。

我需要依赖注入吗?
在这种情况下,基本代码将如何寻找呢? 我是否需要在构造函数中为引用的 DLL 添加一些内容?

1 个答案:

答案 0 :(得分:2)

尝试按照以下方式构建控制器:

public class TestController : Controller
    {     
        IAuthenticationRepository AuthenticationRepository { get;set; }

        public void TestController (IuthenticationRepository authenticationRepository)  
        {
          this.AuthenticationRepository = authenticationRepository;
        }

        public ActionResult Index()
        {
            this.AuthenticationRepository.DeleteUser(1);

            return View();
        }
    }

为您的存储库创建一个接口。然后,您可以使用DI框架(如Ninject for MVC 3)将AuthenticationRepository的实例注入IAuthenticationRepository的使用中。

https://github.com/ninject/ninject/wiki