代码之家  ›  专栏  ›  技术社区  ›  Valentin V

使用Autofac创建元件后自动设置特性

  •  1
  • Valentin V  · 技术社区  · 14 年前

    下面是示例代码:

    public interface IService<TEntity> {        
            IContext Context { get; set; }
            //unimportant methods
            bool Validate(TEntity entity);
            void Add(TEntity enttity);
        }
    
     public class UsersController : Controller {
            private IService<User> _service;
            public MyController(IService<User> service){
                _service = service;
                _service.Context = ControllerContext;
            }
        }
    

    我正在使用AutofacControllerFactory在我的系统中创建控制器ASP.NETMVC应用程序。

    _service.Context = ControllerContext;
    

    换句话说:是否可以使用ControllerContext自动设置此属性? 这应该是可能的,因为每个IService实现都有一个可设置的IContext属性。

    我应该扩展AutofacControllerFactory还是有一个标准的方法?

    1 回复  |  直到 14 年前
        1
  •  2
  •   Community Lee    7 年前

    你所拥有的是 循环依赖

    • UsersController IService<User>
    • iSeries设备<用户> 取决于 ControllerContext
    • 控制器上下文 取决于 用户控制器

    没有DI容器可以进入类的内部并控制那里发生的事情。它们可以为您设置依赖项,并从外部将它们注入到您的类中。但是,它们不能很好地处理循环依赖关系,因此更好的选择是重新设计API。

    从这里看,它很像 IService<TEntity> 是一个 漏泄提取

    事件驱动

    这里是 an article about this sort of problem .

    以下是一个关于ASP.NETMVC问题看起来很像你的问题: Is there a good/proper way of solving the dependency injection loop problem in the ASP.NET MVC ContactsManager tutorial?

    Dependency-Injection to resolve circular dependencies