【问题标题】:Unity Framework: How to Instantiate two classes from the same Interface?Unity Framework:如何从同一个接口实例化两个类?
【发布时间】:2009-03-13 20:25:18
【问题描述】:

我有一个接口和 2 个实现它的类,我需要加载每个类,但统一有:

m_unityContainer.Resolve() // IGeneric接口在哪里

我的配置如下:

      <type type="IGeneric" mapTo="ClassA">
      </type>
      <type type="IGeneric" mapTo="ClassB">
      </type>

有什么想法吗?

谢谢

【问题讨论】:

  • 我需要同时实例化两个类

标签: inversion-of-control unity-container


【解决方案1】:

您还可以使用如下通用接口:

public interface IGeneric{}

public interface IGeneric<T> : IGeneric{}

然后有一个界面的类型安全分辨率:

container.RegisterType<IGeneric<ClassA>, ClassA>();
container.RegisterType<IGeneric<ClassB>, ClassB>();

ClassA classA = container.Resolve<IGeneric<ClassA>>();
ClassB classB = container.Resolve<IGeneric<ClassB>>();

当你走上这条路时,一些有趣的事情开始发生......

【讨论】:

  • 配置中这样的东西:
【解决方案2】:

这将为您提供所有实现 IGeneric 的注册类。

IEnumerable<IGeneric> objects = container.ResolveAll<IGeneric>();

【讨论】:

    【解决方案3】:

    我找到了解决方案,必须在每个条目中使用 name 属性:




    代码看起来像 obj= container.ResolveAll("ClassA");

    【讨论】:

      【解决方案4】:

      沙尔克 - 看起来不错。在 Unity.config 中指定的符号是什么?

      【讨论】:

        【解决方案5】:

        这是一种稍微不同的方式。我正在使用 Unity.2.1.505.2(以防万一)。

          <configSections>
            <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
          </configSections>
        
        
              <unity>
                <container>
                  <register type="IVehicle" mapTo="Car" name="myCarKey" />
                  <register type="IVehicle" mapTo="Truck" name="myTruckKey" />
                </container>
              </unity>
        

        这是 DotNet 代码。

                UnityContainer container = new UnityContainer();
        
                UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
                section.Configure(container);
        
        
        IVehicle v1 = container.Resolve<IVehicle>("myCarKey"); 
        
        IVehicle v2 = container.Resolve<IVehicle>("myTruckKey"); 
        

        见:

        http://msdn.microsoft.com/en-us/library/ff664762(v=pandp.50).aspx

        【讨论】:

          猜你喜欢
          • 2011-07-28
          • 2011-12-31
          • 1970-01-01
          • 1970-01-01
          • 2011-11-30
          • 1970-01-01
          • 1970-01-01
          • 2021-07-18
          • 1970-01-01
          相关资源
          最近更新 更多