Typical IoC container usage - passing data down the line

▼魔方 西西 提交于 2019-11-30 22:42:23
Carl Bergquist

I'm not quite sure that I understand your question. But I don't think you should be passing the container around at all. It's much easier to just create a wrapper class for the container. For example:

public class IoCContainer
{
  private static ContainerType = null;

  public static ContainerType Instance 
  {
    get 
    {
      if (_container == null)
      {
        string configFileName = ConfigurationManager.AppSettings[ConfigFileAppSettingName];
        _container = new WindsorContainer(new XmlInterpreter(configFileName));
      }

      return _container;
    }
  }
}

Now you call this everywhere in your code.

IoCContainer.Instance.Resolve<IAwesomeService>(); 

Does this help you?

I'm not sure if this answers your question, but I would say that a good way to act on an application using the Unity container (also applicable to other IoC engines I think) is:

  • Design your classes so that all the required dependencies are specified in the constructor. This way you don't need to explicitly deal with Unity unless you need to create new objects.
  • If you need to create new objects within your classes, pass the Unity container itself in the constructor as well (as a reference to IUnityContainer), and create all new object instances by using the Resolve method. Even for objects that are not registered and have not dependencies, the container will give you a proper instance, and later you can decide to register types that were not previously registered, without changing the client code.
  • As for passing explicit values to resolved objects, you can specify concrete injection members when you register types (see the InjectionMembers parameter in the RegisterType class).
Kelqualyn

It seems that you need to declare factories for your entities. Resolve factories via constructor injection and pass data values via Create method. All other dependencies must be resolved via factory's constructor.

See this answer.

I'd define a static class IoC, that can be initialized with a particular container and implement methods like Resolve, Resolve(...), which in turn delegate the actual work to the container instance (you'll store this instance in a field or property). This way you don't have to pass anything around, just use

IoC.Resolve<SomeType>();

anywhere in your code.

Regarding the specific data: some containers will take a parameter and resolve depending on this parameter (Autofac has this kind of feature). Or you can always create a factory class that will have a method that accepts a set of parameters (like customer name) and returns a corresponding object instance.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!