开发者

Automatically set property after component creation with Autofac

Here is the example code:

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;
        }
    }

I'm using AutofacControllerFactory to create controllers in my ASP.NET MVC app. Is it possible to eliminate this line of code in every controller's constructor:

_service.Context = ControllerContext;

In other words: is it possible to automatically set this property with ControllerContext? It should be possible because every IService implementation has a settable IContext property.

Should I extend the AutofacControllerFactory or is there a standard way of doint this?


What you have there is a Circular Dependency.

  • UsersController depends on IService<User>
  • IService<User> depends on ControllerContext
  • ControllerContext depends on UsersController

No DI Container can reach into your classes' innards and control what happens there. They can set up dependencies for you and inject them into your classes from the outside. However, they can't very well deal with circular dependencies, so a better option is to redesign the API.

From here it looks very much like the Context property of IService<TEntity> is a Leaky Abstraction. A Service shouldn't need to know anything about the UI framework in which it is running.

You can often break a circular dependency by changing one of the consumers to a more event-driven architecture.

Here's an article about this sort of problem.

Here's a related answer to a ASP.NET MVC question that looks a lot like yours: Is there a good/proper way of solving the dependency injection loop problem in the ASP.NET MVC ContactsManager tutorial?

See also the answer: Dependency-Injection to resolve circular dependencies

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜