【发布时间】:2020-10-15 01:51:05
【问题描述】:
接口设置如下:
public interface IRepository { };
public interface IFirstRepository : IRepository { };
public interface ISecondRepository : IRepository { };
public interface IThirdRepository : IRepository { };
还有一个需要一些但不是所有这些存储库的控制器:
public class TestController : BaseController
{
private IFirstRepository mFirstRepository;
private ISecondRepository mSecondRepository;
// Standard DI for MVC
public TestController(IFirstRepository first, ISecondRepository second)
{
mFirstRepository = first;
mSecondRepository = second;
}
}
而BaseController 看起来像:
public class BaseController : Controller {
public IEnumerable<IRepository> GetRepos()
{
// One solution is to use reflection
// to get all properties that are IRepositories.
// Something along the lines of;
return typeof(this).GetProperties().Where(prop=>prop is IRepository);
// But is there a way to use the AutoFac context
// to get the repos, rather than use reflection?
// it surely already has that info since it
// was able to call the constructor correctly?
}
}
BaseController 有没有办法利用 AutoFac 上下文和现有信息来获取 TestController 请求的 IRepository 实例的集合?
Autofac 肯定已经拥有该信息,因为它能够使用正确的实例调用构造函数。
注意:我在这里不只使用反射的唯一原因是性能问题。
【问题讨论】:
-
我不认为这是可能的,我认为这是糟糕的设计恕我直言,但您可以创建一个类来注入您的存储库集并保存它们,然后在控制器中注入您的一个类
-
嘿@daremachine,这是与现有代码库一起使用的,现有代码库有 50-70 个现有控制器。这里的目标是不必为每个现有控制器单独定义一个列表。
标签: c# asp.net-mvc reflection dependency-injection autofac