【问题标题】:Get resolved dependancies of IRepository with AutoFac使用 AutoFac 获取 A Repository 的已解析依赖项
【发布时间】: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


【解决方案1】:

开箱即用并不是一种简单的方法。如果您发现自己处于这种情况,通常意味着您遇到了界面设计问题。 There's an FAQ walking through an example of why this is, as well as some options.

如果您真的非常需要这样做,那么我可能会考虑添加metadata to each of the registrations,在其中为需要该特定存储库的每个控制器添加一个元数据条目,然后在构造函数中使用metadata filter attribute 进行过滤。同样,the FAQ I mentioned 会遍历此并展示示例。

但如果是在这个系统中工作......我会退后一步,看看我的界面设计,看看如何从一开始就不需要这种过滤器。如果它们都不能被平等对待(Liskov 替换原则),则表明需要不同的接口。

【讨论】:

  • Heya Travis,感谢您的回答。我认为作为解决方案一部分的构造函数可能会误解我在这里想要实现的目标。如果您不介意再看一下,我已经对问题进行了相当大的更新?
  • 更新的问题没有任何意义。 Autofac 会将东西注入到构造函数中。这不是关于聚合属性类型。所以我想答案是“不,Autofac 不这样做”。我仍然会非常非常非常地质疑为什么需要发生这种情况并更改设计以使其不是必需的。
  • 是的,不用担心。我只是想在内部它无论如何都必须做这项工作才能知道将哪些具体类型传递给了哪些构造函数。关于重新设计,这个项目远远超出了可行的程度。听起来我在这里叫错了树,所以将关闭问题并使用反射。再次感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-08
  • 2020-04-13
  • 1970-01-01
  • 2020-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多