Autofac in web applications, where should I store the container for easy access?

前端 未结 5 1053
难免孤独
难免孤独 2020-12-08 23:16

I\'m still pretty new to using Autofac and one thing I miss in the documentation and examples is how to make it easy to get to the configured container from different places

5条回答
  •  無奈伤痛
    2020-12-08 23:30

    The Autofac "way" is to have an IContext constructor parameter. Autofac will inject an object that can be used to resolve types.

    The context is usually the container behind the scenes, IContainer implements the IContext interface, though IContext is limited to only doing resolves.

    I know that the container should not be "overused", but I have, as the OP, classes that requires resolving types that is not known ahead of time (and thus cannot be used as constructor params). I find it useful in these cases, to think of the container as yet another service that can be used to resolve other services, and inject that like any other service.

    If you feel that using IContext binds you to Autofac and you need to abstract that with your own interface this is just a matter of registering an IContext wrapper class with your container.

    Update: in Autofac 2, the IContext is called IComponentContext.

提交回复
热议问题