Исторически у моих контроллеров были объявлены репозитории на каждом контроллере, которые внедряются через 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);
}
}