我刚刚开始使用 IoC 框架,并且一直在使用 Autofac。
在下面的示例代码中,我注册了 2 个完全不同的类(在 global.asax 中),它们都实现了相同的接口(interface),我想知道我们如何确保 Autofac 使用正确的类?目前,我的一个 Controller 将 IPhotoBlogRepository 作为其构造函数,传递一个 PhotoBlogRepository
或一个 TestRepository
,具体取决于下面代码中出现的第一个/最后一个。
builder.RegisterType<PhotoBlogRepository>().As<IPhotoBlogRepository>();
builder.RegisterType<TestRepository>().As<IPhotoBlogRepository>();
最佳答案
这是设计使然。开箱即用的容器无法知道您想要的服务。如果在生产代码中只有一个接口(interface)实现,那么您的注册代码应确保注册的服务不超过一个。
如果您打算支持多种实现,那么您的 Controller 可以依赖 IEnumerable<IPhotoBlogRepository>
. Autofac 将为 Controller 提供实现该接口(interface)的所有注册服务的集合。
如果 Controller 需要更细粒度的控制,请查看 Autofac supports metadata .
也就是说:从您的示例中,我看到您正在注册接口(interface)的测试实现。在单元测试中,我很少从容器中解析 SUT(在这种情况下是您的 Controller ),而是直接实例化它。这消除了用假服务“替换”真实服务的问题,因为您总是将它们直接交给 Controller 构造函数。
关于asp.net-mvc - 使用 Autofac 的 IoC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4369195/