Могу ли я иметь baseController, который имеет все мои репозитории при использовании StructureMap? - PullRequest
1 голос
/ 26 февраля 2011

Исторически у моих контроллеров были объявлены репозитории на каждом контроллере, которые внедряются через StructureMap, и это прекрасно работает для меня.

Но мой новый проект, вероятно, будет использовать те же репозитории для каждого контроллера.В связи с этим я создал BaseController и унаследовал все контроллеры отсюда.Мои репозитории теперь живут в Base, но инъекция не работает.

Может ли это работать так, или инжектор конструктора должен выполняться на каждом контроллере?


        public static void BootStructureMap()
    {
        ObjectFactory.Initialize(x =>
        {
            x.Scan(scanner =>
            {
                scanner.TheCallingAssembly();
                scanner.WithDefaultConventions();
                scanner.AddAllTypesOf<IController>().NameBy(type => type.Name.Replace("Controller", "").ToLower());
            });

            x.For(typeof(IGenericRepository<>)).Use(typeof(GenericRepository<>));
        });
    }

Рабочая:

    public class TransactionController : Controller
{
    public IGenericRepository<ITransaction> TransactionRepository { get; set; }

    public TransactionController(IGenericRepository<ITransaction> transactionRepository)
    {
        this.TransactionRepository = transactionRepository;
    }


    public ActionResult Index()
    {
        var transactions = this.TransactionRepository.Query.AsEnumerable();
        return View(transactions);
    }

Не работает:

    public class BaseController : Controller
{
    public IGenericRepository<ITransaction> TransactionRepository { get; set; }

    public BaseController(IGenericRepository<ITransaction> transactionRepository)
    {
        this.TransactionRepository = transactionRepository;
    }

    protected BaseController()
    {

    }
}


public class TransactionController : BaseController
{
    public ActionResult Index()
    {
        var transactions = base.TransactionRepository.Query.AsEnumerable();
        return View(transactions);
    }

}

Ответы [ 2 ]

3 голосов
/ 26 февраля 2011

Вы должны как-то добавить свой репозиторий в BaseController. Если ваш последний фрагмент кода является реальным кодом, который у вас есть, то, похоже, BaseController инициализируется через защищенный конструктор без параметров.

Добавить конструктор к TransactionController:

public TransactionController(IGenericRepository<ITransaction> transactionRepository) : base(transactionRepository)
{
}
0 голосов
/ 27 февраля 2011

Можно использовать инъекцию зависимостей бедного человека - используется в приложении NerdDinner

public BaseController() : this(new  Message())
{
}

Или Ссылка Филла TDD-и-зависимость закачка-с asp.net-mvc.aspx

Override DefaultControllerFactory 
public class SMControllarFactory : DefaultControllerFactory

В

application start 
protected void Application_Start()
{
    ControllerBuilder.Current.SetControllerFactory(new SMControllarFactory());
...