#entity-framework #asp.net-mvc-3
#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:
Попробуйте структурировать свой контроллер следующим образом:
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 для MVC 3), чтобы внедрить экземпляры AuthenticationRepository в обычаи IAuthenticationRepository.